16

次のメソッドを使用して、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);
}
4

3 に答える 3

27

質問で説明したことを行う方法を理解し、他の人の利益のために投稿する必要があると考えました。コードは以下のとおりです。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);
}
于 2014-06-12T21:30:29.313 に答える
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);
}
于 2014-07-29T16:05:33.023 に答える