Daniel
Daniel

Reputation: 11

Have you tried Class AudioTrack in Android with a buffer size which is a power of two?

I'm working in one application for Android with class AudioTrack, and sometimes I get the exception "Invalid audio buffer size". Since I'm planning to use FFT, I make the buffer size a power of two, and since then, sometimes I get this exception. Any ideas why is that?

Thanks, Daniel

My code is very straight forward:

private void playTrack(short []buffer){
        try{
            Log.i(TAG,"Play track, Buffer size: "+buffer.length );
            AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                    mAudioIn.getFrequency(),
                    mAudioIn.getChannelConfig(),
                    mAudioIn.getAudioEncoding(),
                    buffer.length,
                    AudioTrack.MODE_STREAM);
            audioTrack.play();

            audioTrack.write(buffer, 0, buffer.length);
        }catch(Throwable t){
            Log.e(TAG,"Play track, something's wrong: "+t.getMessage()+ " When buffer size is:"+buffer.length );
        }

    }`enter code here`

Upvotes: 1

Views: 1694

Answers (2)

Fernando Dos Santos
Fernando Dos Santos

Reputation: 31

I just realized, you can't use an odd number as the buffer size. Try taking your size and doing something like this:

if (size % 2 == 1)
    size++;`

This will make an odd number even.

Upvotes: 3

Chris McGrath
Chris McGrath

Reputation: 1936

Try calling something like

_audioTrackSize = android.media.AudioTrack.getMinBufferSize(
            audioSampleRate, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
            AudioFormat.ENCODING_PCM_16BIT);

and then round the returned minimum size up to a power of two.

Upvotes: 0

Related Questions