I want to read the audio file from sdcard into byte array. and play the file using this byte array into AudioTrack.
Like AudioTrack play file in this way
track.play();
track.write(byte_Arr,0,byte_Arr.length);
I want to read the audio file from sdcard into byte array. and play the file using this byte array into AudioTrack.
Like AudioTrack play file in this way
track.play();
track.write(byte_Arr,0,byte_Arr.length);
The simplest way to play audio in such a scenario is to read a "wav" file. If you want to read another format such as "mp3" you will have to use another audio player class such MediaPlayer
. An example of its usage is as follows:
String filePath = Environment.getExternalStorageDirectory()+"/yourfolderName/yourfile.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.start();
If you still want to use AudioTrack for playing then you need a decoder. This can be a much complicated task so we will carry on "wav" files.
A "wav"file has an header like other formats such as "mp3".
In order to do this, you have to read the header. You have to find out the sample rate, bit depth, and channels configuration of the file. You can find out how to get those from a header by a research. I'm not sure if you actually want to read a "wav" file so not giving further details on headers but you may check this out:
If you simply know the sample rate, bit depth and channel configuration then you may bypass the header. It usually occupies the first 44 bytes of the file then the raw PCM data follows. You may read that data with BufferedReader
.
String filePath = Environment.getExternalStorageDirectory()+"/yourfolderName/yourfile.wav";
BufferedReader br = new BufferedReader(new FileReader(filePath));
File mFile = new File(filePath);
long fLength = mFile.length();
char[fLength - 44] buffer;
br.Read(buffer, 44, fLength - 44);
br.close();
// Additional tasks...
I'm not sure about the previous code above because I didn't try it.
Instead of reading byte array from Audio file, you can set the path like this
MediaPlayer mp = new MediaPlayer();
mp.setDataSource("/mnt/sdcard/yourdirectory/youraudiofile.mp3");
mp.prepare();
mp.start();