我正在通过websockets接收原始的float32音频,并希望在浏览器中播放此音频。据我所知,我需要使用MediaStream应用程序接口。但是,我找不到一种方法来创建一个可以附加数据缓冲区的MediaStream。
实现这一目标的正确方法是什么?
我正在尝试这样的东西:
var context = new AudioContext();
context.sampleRate = 48000;
var stream = null; // ????
var source = context.createMediaStreamSource(stream);
source.connect(context.destination);
source.start(0);
socket.onmessage = function (event) {
stream.appendBuffer(new Float32Array(event.data)); // ????
};发布于 2018-10-31 16:31:57
您应该使用AudioBuffers从websocket的缓冲区中读取声音并播放它。
var context = new AudioContext();
var sampleRate = 48000;
var startAt = 0;
socket.onmessage = function (event) {
var floats = new Float32Array(event.data);
var source = context.createBufferSource();
var buffer = context.createBuffer(1, floats.length, sampleRate);
buffer.getChannelData(0).set(floats);
source.buffer = buffer;
source.connect(context.destination);
startAt = Math.max(context.currentTime, startAt);
source.start(startAt);
startAt += buffer.duration;
};这将播放来自网络插座的音乐。
要将AudioBuffer转换为MediaStream,请使用AudioContext.createMediaStreamDestination()。将BufferSource连接到它,以基于缓冲区的数据创建自定义MediaStream。
var data = getSound(); // Float32Array;
var sampleRate = 48000;
var context = new AudioContext();
var streamDestination = context.createMediaStreamDestination();
var buffer = context.createBuffer(1, data.length, sampleRate);
var source = context.createBufferSource();
buffer.getChannelData(0).set(data);
source.buffer = buffer;
source.connect(streamDestination);
source.loop = true;
source.start();
var stream = streamDestination.stream;这将从数据数组中读取音频并将其转换为MediaStream。
发布于 2018-10-31 23:47:41
关于解码,来自窗口对象的audioContext应该可以完成这项工作。
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();然后
audioCtx.decodeAudioData(audioData, function(buffer) {直接在二进制数组上。
关于通信,我更喜欢使用XMLHttpRequest (一个低级函数和旧函数),并直接使用响应。
这是一个由MDM家伙制作的非常好的函数(我更新了ogg文件的url,以便您可以直接测试它):
function getData() {
source = audioCtx.createBufferSource();
request = new XMLHttpRequest();
request.open('GET', 'https://raw.githubusercontent.com/mdn/webaudio-examples/master/decode-audio-data/viper.ogg', true);
request.responseType = 'arraybuffer';
request.onload = function() {
var audioData = request.response;
audioCtx.decodeAudioData(audioData, function(buffer) {
myBuffer = buffer;
songLength = buffer.duration;
source.buffer = myBuffer;
source.playbackRate.value = playbackControl.value;
source.connect(audioCtx.destination);
source.loop = true;
loopstartControl.setAttribute('max', Math.floor(songLength));
loopendControl.setAttribute('max', Math.floor(songLength));
},
function(e){"Error with decoding audio data" + e.error});
}
request.send();
}完整的源代码在这里:
https://raw.githubusercontent.com/mdn/webaudio-examples/master/decode-audio-data/index.html
https://stackoverflow.com/questions/22934925
复制相似问题