2014-06-10 2 views
9

다음 방법을 사용하여 wav 데이터가 들어있는 바이트 배열을 재생하고 있습니다. 이 함수는 GWT 프로젝트에서 호출됩니다.javascript/html5를 통해 wav 오디오 바이트 배열을 재생하는 방법은 무엇입니까?

이 기능은 소리를 재생하지만, 일종의 헬리쉬 (Hellish) 괴물처럼 들립니다. 샘플 속도는 확실히 정확합니다 (소리는 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); 
} 

답변

17

나는 내 질문에 설명 된 것을 수행하고 다른 사람들을 위해 게시해야한다고 생각했습니다. 코드는 다음과 같습니다. 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); 
} 
+0

큰 물건, 나는이 같은 간결한, 삶은 다운 예를 들어 찾아 봤는데

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); } 

관련 문제