How to calculate the audio amplitude in real time (android)

后端 未结 3 1870
灰色年华
灰色年华 2021-01-05 23:33

I am working on an Android app where I need to calculate the audio amplitude in real time. As of now I am using MediaPlayer to play the track. Is t

相关标签:
3条回答
  • 2021-01-05 23:49

    Your problem lies in the improper conversion of 16-bit samples to double precision. First you need to convert two adjacent bytes to an int and then do the conversion to double. For example

    double amplitude = 0;
    for (int i = 0; i < audioData.length/2; i++) {
        double y = (audioData[i*2] | audioData[i*2+1] << 8) / 32768.0
        // depending on your endianness:
        // double y = (audioData[i*2]<<8 | audioData[i*2+1]) / 32768.0
        amplitude += Math.abs(y);
    }
    amplitude = amplitude / audioData.length / 2;
    

    Please note that your code and my answer are both assuming one channel of data. If you have more than one channel you'll need to be careful to separate the amplitudes as the data will be interleaved L,R,L,R (after the conversion to double).

    0 讨论(0)
  • 2021-01-06 00:00

    Did you try with that solution?

    // Calc amplitude for this waveform
    float accumulator = 0;
    for (int i = 0; i < data.bytes.length - 1; i++) {
      accumulator += Math.abs(data.bytes[i]);
    }
    
    float amp = accumulator/(128 * data.bytes.length);
    
    0 讨论(0)
  • 2021-01-06 00:07

    Use this example:

    http://androidexample.com/Detect_Noise_Or_Blow_Sound_-_Set_Sound_Frequency_Thersold/index.php?view=article_discription&aid=108&aaid=130

    Hope this solves your problem....cheerz

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