Подтвердить что ты не робот

DecodeAudioData HTML5 Audio API

Я хочу воспроизводить аудиоданные из ArrayBuffer... поэтому я создаю свой массив и заполняю его микрофонным вводом. Если я рисую эти данные на холсте, это выглядит как → enter image description here

Итак, это работает!

Но если я хочу слушать эти данные с помощью

context.decodeAudioData(tmp, function(bufferN) { //tmp is a arrayBuffer
    var out = context.createBufferSource();
    out.buffer = bufferN;
    out.connect(context.destination);
    out.noteOn(0);
}, errorFunction);

Я ничего не слышу... потому что вызывается функция errorFunction. Но ошибка равна нулю!

Я также попытался получить такой буфер:

var soundBuffer = context.createBuffer(myArrayBuffer, true/*make mono*/);

Но я получаю сообщение об ошибке: Uncaught SyntaxError: указана недопустимая или недопустимая строка.

кто-нибудь, кто может дать мне подсказку?

EDIT 1 (больше кода и как я получаю микрофонный вход):

 navigator.webkitGetUserMedia({audio: true}, function(stream) {

                liveSource = context.createMediaStreamSource(stream);

                // create a ScriptProcessorNode
                if(!context.createScriptProcessor){
                   node = context.createJavaScriptNode(2048, 1, 1);
                } else {
                   node = context.createScriptProcessor(2048, 1, 1);
                }


                node.onaudioprocess = function(e){

               var tmp = new Uint8Array(e.inputBuffer.byteLength);
               tmp.set(new      Uint8Array(e.inputBuffer.byteLength), 0);

   //Here comes the code from above.

Спасибо за вашу помощь!

4b9b3361

Ответ 1

Возвращенная ошибка из функции обратного вызова равна нулю, поскольку в текущем webaudio api spec эта функция не возвращает ошибку объекта

callback DecodeSuccessCallback = void (AudioBuffer decodedData);
callback DecodeErrorCallback = void ();

    void decodeAudioData(ArrayBuffer audioData,
                         DecodeSuccessCallback successCallback,
                         optional DecodeErrorCallback errorCallback);

DecodeSuccessCallback возникает, когда полный вход ArrayBuffer декодируется и хранится внутри как AudioBuffer, но по неизвестной причине decodeAudioData не может декодировать прямой поток.

Вы можете попытаться воспроизвести захваченный буфер, установив выходные данные буфера при обработке аудио

function connectAudioInToSpeakers(){

  //var context = new webkitAudioContext();  
  navigator.webkitGetUserMedia({audio: true}, function(stream) {

    var context = new webkitAudioContext();  
    liveSource = context.createMediaStreamSource(stream);

    // create a ScriptProcessorNode
    if(!context.createScriptProcessor){
       node = context.createJavaScriptNode(2048, 1, 1);
    } else {
       node = context.createScriptProcessor(2048, 1, 1);
    }


    node.onaudioprocess = function(e){

        try{
            ctx.clearRect(0, 0, document.getElementById("myCanvas").width, document.getElementById("myCanvas").height);
            document.getElementById("myCanvas").width = document.getElementById("myCanvas").width;
            ctx.fillStyle="#FF0000";

            var input = e.inputBuffer.getChannelData(0);
            var output = e.outputBuffer.getChannelData(0);
            for(var i in input) {
                output[i] = input[i];
                ctx.fillRect(i/4,input[i]*500+200,1,1);
            }


        }catch (e){
            console.log('node.onaudioprocess',e.message);
        }

    }

     // connect the ScriptProcessorNode with the input audio
    liveSource.connect(node);
    // if the ScriptProcessorNode is not connected to an output the "onaudioprocess" event is not triggered in chrome
    node.connect(context.destination);

    //Geb mic eingang auf boxen
    //liveSource.connect(context.destination);
  });
}

Ответ 2

Через некоторое время я снова попытался решить эту проблему и нашел решение:

https://developer.mozilla.org/en-US/docs/Web/API/ScriptProcessorNode

Совсем не сложно, поэтому я создал рабочую скрипку:

https://jsfiddle.net/WEM3y/

Итак, активируйте свой микрофон (проверено на chrome v35) и проверьте его.

Часть я изменилась:

node.onaudioprocess = function(e){

    var outData = e.outputBuffer.getChannelData(0);
    var inData = e.inputBuffer.getChannelData(0);

    // Loop through the 4096 samples, copy them to output buffer
    for (var sample = 0; sample < e.outputBuffer.length; sample++) {
      // Set the data in the output buffer for each sample
      outData[sample] = inData[sample]; //Modify your buffer here if you want
    }
}