在 react-native-track-player 库的帮助下,尝试使用 React native 和 Nodjs 创建一个真正的音频流应用程序和服务器来播放音频。一切正常,但是当涉及到来自服务器的真正实时流时,react-native-track-player 没有发送任何内容范围,因此服务器将使用内容范围响应部分内容 206 状态。
有人对此有所了解吗?
这是我为服务器准备的:
const getLocalFileSubLocation = async (req, res) => {
const { location, sub_location, filename } = req.params
const fileLocation = path.join(UPLOAD_DIR, location, sub_location, filename)
if (!fs.existsSync(fileLocation)) return Resp.notFound(res)
const fileSize = fs.statSync(fileLocation).size
const contentType = mimeTypes.lookup(fileLocation)
if (contentType !== 'audio/mpeg') return fs.createReadStream(fileLocation).pipe(res)
const range = req.headers.range ? req.headers.range : "bytes=0-"
const CHUNK_SIZE = 10 ** 6 / 2; // 1mb
let [start, end] = range.replace(/bytes=/, "").split("-")
start = parseInt(start, 10)
end = start + CHUNK_SIZE
res.writeHead(206, {
"Content-Range": `bytes ${start}-${end}/${fileSize}`,
"Accept-Ranges": "bytes",
"Content-Length": end - start + 1,
"Content-Type": contentType,
});
fs.createReadStream(fileLocation, { start, end }).pipe(res)
}
router.get("/:location/:sub_location/:filename", getLocalFileSubLocation)
另一方面音频播放器:
await TrackPlayer.setupPlayer({
maxCacheSize: 1048576,
waitForBuffer: true,
});
export const onAddTrack = async (song: any) => {
const track: Track = {
id: song._id,
title: song.title,
url: FILE_URL + song.url,
artist: song.singer?.name,
description: song.description,
artwork: FILE_URL + song.cover,
};
await TrackPlayer.add(track);
};
这是标题的样子:
{ 'icy-metadata': '1',
'user-agent':
'react-native-track-player/1.0 (Linux;Android 11) ExoPlayerLib/2.11.4',
'accept-encoding': 'identity',
host: '143.244.142.104:8000',
connection: 'Keep-Alive' }
这是流式 uri 的示例:http://143.244.142.104:8000/file/songs/audios/default.mp3