0

I want to read 1024 bytes at a time using FileInputStream, and pass the byte buffer to AudioTrack which will play the 1024 bytes. I have put this is a while loop so that the entire track is played continuously. You might suggest that you could read the entire PCM at once, but I do not want to do that. This snippet of code plays only the first 1024 bytes, and exits the loop after that.

                    fis = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Notate/" + MainActivity.filepath);
l = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Notate/" + MainActivity.filepath);
                byte[] buffer = new byte[1024];
                try {
                    fis = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Notate/" + MainActivity.filepath);


                    while (fis.read(buffer)!=-1) {

                    int intSize = android.media.AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_OUT_MONO,
                            AudioFormat.ENCODING_PCM_16BIT);
                    AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_OUT_MONO,
                            AudioFormat.ENCODING_PCM_16BIT, intSize, AudioTrack.MODE_STREAM);
                    TextView t1 = (TextView) contentView.findViewById(R.id.textView1);
                    t1.setText(Integer.toString(intSize));
                    if (at != null) {
                        at.play();
                        at.write(buffer, 0, buffer.length);
                        at.stop();
                        at.release();
                    }
                }
                    fis.close();
                } catch (Exception e) {
                }
shivram
  • 469
  • 2
  • 10
  • 26
  • Please indent your code so that it's readable. I see two `try` blocks in your code, but only one `catch`. Where's the other one? Also, when an exception occurs you might want to at least log the exception so that you know what's happening. – Michael Jan 07 '15 at 07:57
  • And you're trying to create a new `AudioTrack` for every iteration of the `while` loop. You should be creating a single `AudioTrack` _before_ the loop. – Michael Jan 07 '15 at 07:59

1 Answers1

0

You need to be more accurate in accounting for the bytes actually produced by the read...

from the docs on read(byte[])...

Returns:

the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.

But you assume an entire buffer.length has been deliver?

Where is the case where the return value of the read is NONEoF ( -1 , 1024 ) ?

You must account for that edge case in your code by writing exactly what length delivered by the previous read .

Robert Rowntree
  • 6,230
  • 2
  • 24
  • 43