HTML5 Audio API inputBuffer.getChannelData to audio Array buffer

旧时模样 提交于 2019-12-06 15:09:26

If I'm understanding this correctly (there are some missing pieces in your code sample)...

decodeAudioData can only decode things like MP3 or WAV. It looks like you're passing it a raw Int16Array or Uint16Array. Because the underlying ArrayBuffer isn't a format that decodeAudioData understands, it gives up.

I think what you want to do is something like this:

function playsound( raw ) {
  // i'll assume you know how to convert in this direction
  // since you have convertFloat32ToInt16
  var buffer = convertInt16ToFloat32( raw ),
    src = context.createBufferSource(),
    audioBuffer = context.createBuffer( 1, buffer.length, context.sampleRate );
  audioBuffer.getChannelData( 0 ).set( buffer );
  src.buffer = audioBuffer;
  src.connect( context.destination );
  src.start( 0 );
}

Basically, you already have a way to create the raw Float32Array that the Web Audio API likes, so there's no need to decode (and you can't decode anyway, since your data isn't a valid file format). So you just convert back to Float32Array, create your own AudioBuffer, write in the data from buffer, and go from there.

For converting from float32 to unsigned int 16 you can multiply each float32 value with 0xffff(which is 16 bit max value). and for int16 to float32 do this reversely which means divide by 0xffff. audio should be fine now.

I am new in stackoverflow. I should write this as a comment but due to lack of reputation point i can't. Thats why i have to write it as a answer. sorry for inconvenience.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!