Question

I'm having some trouble with reading and playing certain audio clips on Android 2.0.1 (Motorola Droid A855). Below is the code segment that I use. It works fine for some files, but for other files it just doesn't exit the while loop. I have tried checking

InputStream.available()

method but with no luck. I even printed out the number of bytes it reads properly before getting stuck. It seems that it gets stuck in the loop at the last round of read (have less than < 512 bytes left), and doesn't exit the loop.

    int sampleFreq = 44100;
    int minBufferSize = AudioTrack.getMinBufferSize(sampleFreq, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
    int bufferSize = 512;
    AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, sampleFreq, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);


    InputStream input;
    try {
        File fileID=new File(Environment.getExternalStorageDirectory(),resourceID);
        input = new FileInputStream( fileID);
        int filesize=(int)fileID.length();
        int i=0,byteread=0;     
        byte[] s = new byte[bufferSize];

        at.play();
        while((i = input.read(s, 0, bufferSize))>-1){
             at.write(s, 0, i);
             //at.flush(); 
             byteread+=i;
             Log.i(TAG,"playing audio "+byteread+"\t"+filesize);
        }

        at.stop();  
        at.release();
        input.close();


    } catch (FileNotFoundException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    }       

Audio files are around 1-2MB in size and are in wav format. Following is an example of the logging-

> : playing audio 1057280   1058474
> : playing audio 1057792   1058474
> : playing audio 1058304   1058474

Any idea why this is happening as it runs perfectly for some of the audio files.

Was it helpful?

Solution

Make sure your call to write() always delivers a byte size which is an integral number of samples.

For your 16 bit stereo mode, that should be an integral multiple of 4 bytes.

Additionally, at least before the final write, for stutter-free operation you should really respect the minimum buffer size of the audio subsystem and deliver at least that much data in each call to the audio write method.

If your source data is a .wav file, make sure you actually skip the header and read samples only starting from a valid payload chunk.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top