bre*_*rit 13 javascript gwt html5 wav audiocontext
我正在使用以下方法来播放包含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);
}
Run Code Online (Sandbox Code Playgroud)
bre*_*rit 21
我想出了如何做我在我的问题中所描述的内容,并认为我应该发布它以造福他人.代码如下.我调用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);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
清理建议:
function playByteArray( bytes ) {
var buffer = new Uint8Array( bytes.length );
buffer.set( new Uint8Array(bytes), 0 );
context.decodeAudioData(buffer.buffer, play);
}
function play( audioBuffer ) {
var source = context.createBufferSource();
source.buffer = audioBuffer;
source.connect( context.destination );
source.start(0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18118 次 |
| 最近记录: |