HTML5 Web Audio API, porting from javax.sound and getting distortion

前端 未结 2 926
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 02:38

I have a requirement to generate audio on the fly (generating from wav or mp3 files is not an option). Luckily the new WebAudio API (FF4 and Chrome 13) provides this functio

相关标签:
2条回答
  • 2021-01-07 02:52

    You can do this without the Web Audio API since you have the sample data. Generate a .wav file on the fly and use type arrays.

    Slide 23: http://davidflanagan.com/Talks/jsconf11/BytesAndBlobs.html

    0 讨论(0)
  • 2021-01-07 03:03

    Thanks to the very helpful Google Chrome team, I figured this one out. Here is what they said:

    Hi Brad, it looks like your sample-data is outside of the valid range. For this API, the full-scale floating-point PCM audio data should be within the range -1.0 -> +1.0

    Perhaps your data values are 16bit scaled (-32768 -> +32767).

    So when I create my byte array, I need to make sure everything is represented as a decimal. So instead of this:

    byte[] buffer = new byte[]{ 56, -27, 88, -29, 88, ............ };
    

    I really needed something that looked like this:

    byte[] buffer = new byte[]{ 0.023, -0.1, 0.125, -0.045, ............ };
    

    So in my code I just added some logic to convert the 16bit scaled values to the appropriate range like this:

    for(var i=0;i<buffer.length;i++) {
       var b = buffer[i];
       b = (b>0)?b/32767:b/-32768;
       buffer[i] = b;
    }
    

    Now the audio is represented as a decimal and no longer sounds like a distorted heavy metal song.

    0 讨论(0)
提交回复
热议问题