Playing music/audio file in Android

string mediaFilePath = "PATH TO YOUR MUSIC/AUDIO FILE";
File mediafile = new File(mediaFilePath);
short[] audio = new short[(int) (mediafile.length()/2)];
AudioTrack audiotrack = new AudioTrack(
                    AudioManager.STREAM_MUSIC,
                    11025,
                    AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    audio.length,
                    AudioTrack.MODE_STREAM
                    );
 
audiotrack.play();
audiotrack.write(audio, 0, audio.length);
// To pause use code below
//audiotrack.pause();
// To stop use code below
//audiotrack.stop();
// release all resources
audiotrack.release();

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.