我目前正在开发一个移动应用程序项目(react-native 中的前端和 nodeJS 中的后端),目标是允许用户直接在应用程序中(特别是在后台无缝地)播放 Spotify 歌曲。目标是通过消除 Spotify 应用程序中手动播放操作的需要来增强用户体验。
有一个API:https://developer.spotify.com/documentation/web-api
我还没有看一下 android-api,我告诉自己,如果我有一个后台节点,我需要 web api。
我已成功使用这些文档生成了一个重定向到我的 PC 上的 Spotify 的链接。然而,它只带我到曲目页面,而不播放声音。此外,我还获得了一个适合“音频”元素的链接,但它提供了一个持续时间为 30 秒的 Preview_url,有时返回为“null”。我想强调的是,这是在PC上,而不是在移动设备上。如果有人对如何实现后台播放有见解、解决方案或想法或遇到过类似情况,我将非常感谢您的帮助!
const express = require("express");
const { SpotifyApi } = require("@spotify/web-api-ts-sdk");
const cors = require("cors");
const app = express();
const port = 3000;
app.use(cors());
const api = SpotifyApi.withClientCredentials(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
);
app.get("/testSpotify", async (req, res) => {
try {
const trackId = "7J1uxwnxfQLu4APicE5Rnj?si=7ec56c19fc924afe";
const trackInfo = await getTrackInfo(trackId);
const trackUrlPreview = trackInfo.preview_url;
const trackUrlSpotify = trackInfo.external_urls.spotify;
res.json({ trackUrlPreview, trackUrlSpotify });
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
});
async function getTrackInfo(trackId) {
const response = await api.tracks.get(trackId);
return response;
}
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Music Player</title>
</head>
<body onload="getTrack()">
<audio id="musicPlayer" controls></audio>
<a href="" id="goSpotify">Go Spotify</a>
<script>
const musicPlayer = document.getElementById("musicPlayer");
const goSpotify = document.getElementById("goSpotify");
async function getTrack() {
try {
const response = await fetch("http://localhost:3000/testSpotify");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log(data);
musicPlayer.src = data.trackUrlPreview;
goSpotify.href = data.trackUrlSpotify;
} catch (error) {
console.error("Error:", error.message);
}
}
</script>
</body>
</html>
您需要应用程序远程:https://spotify.github.io/android-sdk/app-remote-lib/docs/才能控制Spotify应用程序。
此外,Spotify 还会广播一些您可能会听到的意图。