我制作了一个 expressjs 服务器,它有一个“歌曲”路由,提供 .mp3 文件。歌曲路线代码:
import express from "express"
const path = require("path")
const router = express.Router()
...
router.get("/download/:filename", (req, res, next) => {
// 'test.mp3' is located in the same folder as this file
const file = path.join(__dirname, `${req.params.filename}`)
res.download(file)
})
module.exports = router
我遵循“react-native-track-player”中的“入门”会话并复制代码进行测试,但从我的服务器请求“test.mp3”。音乐播放器代码:
export default function PlayerComponent() {
const playbackState = usePlaybackState();
useEffect(() => {
setup();
}, []);
async function setup() {
await TrackPlayer.setupPlayer({});
await TrackPlayer.updateOptions({
stopWithApp: false,
capabilities: [
TrackPlayer.CAPABILITY_PLAY,
TrackPlayer.CAPABILITY_PAUSE,
TrackPlayer.CAPABILITY_SKIP_TO_NEXT,
TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS,
TrackPlayer.CAPABILITY_STOP,
],
compactCapabilities: [
TrackPlayer.CAPABILITY_PLAY,
TrackPlayer.CAPABILITY_PAUSE,
],
});
}
async function togglePlayback() {
const currentTrack = await TrackPlayer.getCurrentTrack();
// Creating a test track
const track = {
id: '111',
url: 'http://X.X.X.X:5000/api/songs/download/test.mp3', // My Express server URL
title: 'Test',
artist: 'myself',
genre: 'Pop Music',
date: '2014-05-20T07:00:00+00:00',
artwork:
'https://images.genius.com/23eaf0161396f67cc3bf264ca148a2b7.668x668x1.jpg',
};
if (currentTrack === null) {
await TrackPlayer.add(track);
await TrackPlayer.play();
} else {
if (playbackState === TrackPlayer.STATE_PAUSED) {
await TrackPlayer.play();
} else {
await TrackPlayer.pause();
}
}
}
return (
<View style={{flex: 1}}>
<LinearGradient
colors={['#120D14', '#C00EFF']}
start={{x: 0.5, y: 0.7}}
end={{x: 0.5, y: 0}}
style={{flex: 1, justifyContent: 'center'}}>
<View style={styles.container}>
<View style={styles.topArea}>
<MaterialIcons name="keyboard-arrow-down" size={35} color="white" />
</View>
<Player
onNext={skipToNext}
onPrevious={skipToPrevious}
onTogglePlayback={togglePlayback}
/>
</View>
</LinearGradient>
</View>
);
}
但是在单击播放按钮(即在播放器组件内)后,音乐不会播放。但是,当我使用文档提供的轨道时,它工作得很好。(代码波纹管):
const track = {
id: '1111',
url:
'https://drive.google.com/uc?export=download&id=1AjPwylDJgR8DOnmJWeRgZzjsohi-7ekj',
title: 'Longing',
artist: 'David Chavez',
artwork: 'https://i.picsum.photos/id/100/200/200.jpg'
};
这让我想到问题出在我的 expressjs 服务器上。所以我开始做一些测试,并没有发现任何太意外的东西。我唯一意识到的是,当使用 PostMan 请求下载文件时,会以 .mpga 扩展名下载两个文件,而在浏览器中,所需文件 (test.mp3) 是 .mp3 格式(即预计会发生)。我不确定这是否意味着什么,但这就是我想出来的。
我做过的事情
- 我已经检查并确认请求是否是由客户提出的。
- 我尝试使用“sendFile()”而不是“download()”,但没有成功。
任何帮助表示赞赏,我希望我说清楚了。提前致谢