我有一个后端脚本,服务音频文件作为流。 如何从react前端服务播放文件流?
附注。 当我从浏览器中点击URL时,音频元素会自动创建音频流。
const cors = require('cors')
const fs = require('fs')
const app = express()
const port = 5000
app.get('/',cors(), function (req, res) {
var file = './audio.mp3'
var stream = fs.createReadStream(file)
res.setHeader('Content-Type','audio/mpeg')
stream.on("data",(chunk) => {
console.log("streaming");
res.write(chunk)
})
});
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}))```
多亏了@费哈特,我一分钟就想通了。 将对象的URL存储在一个状态中,并将其与一个音频元素连线。
state = {
songUrl : ""
}
sendRequest = () => {
this.setState({songUrl : "http://localhost:5000"})
}
render(){
<audio src={this.state.songUrl} controls={this.state.songUrl===''?'':'visible'}/>
}