gpt4 book ai didi

javascript - 如何使用节点服务器进行实时音频流传输?

转载 作者:行者123 更新时间:2023-12-03 02:28:20 25 4
gpt4 key购买 nike

我想制作现场音频流。我从节点服务器通过管道传输mp3文件,没有问题。我在客户端播放mp3,但仅在流结束时播放。我想在流继续播放时播放它。我该怎么做?

服务器端

   var stream = ss.createStream();
ss(socket).emit('H_to_S_shareVoice', stream);
var filename = 'musix' + '.mp3';
console.log(filename);
fs.createReadStream(filename).pipe(stream);

客户

<br>
<br>
<h1 id='socket'>not connected</h1>
<br>
<audio autoplay volume="1" controls id="audio" />



    $(document).ready(function () {

$(function () {
var socket = io.connect('http://localhost:4000');


socket.on("connect", function () {
console.log("on connect");
document.getElementById('socket').innerHTML = 'connected to the server';

ss(socket).on('H_to_S_shareVoice', function (stream, data) {
console.log('received', data);

var binaryString = "";
stream.on('data', function (data) {
console.log('data')
console.log(data.length)
for (var i = 0; i < data.length; i++) {
binaryString += String.fromCharCode(data[i]);
}
$("#audio").attr("src", "data:audio/wav;base64," + window.btoa(binaryString));
document.getElementById('audio').load();
document.getElementById('audio').play();
//document.getElementById('test').innerHTML = window.btoa(binaryString);
/*if (dat.length > 0 && oneTime) {
oneTime = false;

}*/
// $("#audio").attr("src", "data:audio/wav;base64," + window.btoa(binaryString));


binaryString = ""
});

/*stream.on('end', function (data) {
console.log('end')
document.write(binaryString);
$("#audio").attr("src", "data:audio/wav;base64," + window.btoa(binaryString));

binaryString = "";
});*/
});
});
});
});

</script>

最佳答案

删除所有Socket.IO代码,以及整个base64编码混乱。

您要做的就是在请求传入时通过HTTP输出媒体数据。您的客户端代码就像<audio src="path/on/the/server"></audio>一样简单。

关于javascript - 如何使用节点服务器进行实时音频流传输?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52073811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com