我正在使用以下方法来播放包含 wav 数据的字节数组。该函数是从 GWT 项目调用的。
这个函数会播放声音,但听起来像是某种地狱怪物。采样率绝对是正确的(声音是由 neospeech 生成的),并且我已经尝试了 numberOfSamples 的各种值,这似乎代表了音频数据的长度。
numberOfSamples 的值大于 30000 将播放音频文件的完整长度,但它是乱码并且很糟糕。
那么,我做错了什么?
function playByteArray(byteArray, numberOfSamples) {
sampleRate = 8000;
if (!window.AudioContext) {
if (!window.webkitAudioContext) {
alert("Your browser does not support any AudioContext and cannot play back this audio.");
return;
}
window.AudioContext = window.webkitAudioContext;
}
var audioContext = new AudioContext();
var buffer = audioContext.createBuffer(1, numberOfSamples, sampleRate);
var buf = buffer.getChannelData(0);
for (i = 0; i < byteArray.length; ++i) {
buf[i] = byteArray[i];
}
var source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(audioContext.destination);
source.start(0);
}
我想出了如何做我在问题中描述的事情,并认为我应该为了其他人的利益而发布它。代码如下。我调用 playByteArray 并向其传递一个包含 pcm wav 数据的字节数组。
window.onload = init;
var context; // Audio context
var buf; // Audio buffer
function init() {
if (!window.AudioContext) {
if (!window.webkitAudioContext) {
alert("Your browser does not support any AudioContext and cannot play back this audio.");
return;
}
window.AudioContext = window.webkitAudioContext;
}
context = new AudioContext();
}
function playByteArray(byteArray) {
var arrayBuffer = new ArrayBuffer(byteArray.length);
var bufferView = new Uint8Array(arrayBuffer);
for (i = 0; i < byteArray.length; i++) {
bufferView[i] = byteArray[i];
}
context.decodeAudioData(arrayBuffer, function(buffer) {
buf = buffer;
play();
});
}
// Play the loaded file
function play() {
// Create a source node from the buffer
var source = context.createBufferSource();
source.buffer = buf;
// Connect to the final output node (the speakers)
source.connect(context.destination);
// Play immediately
source.start(0);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)