Playing audios directly without downloading it is an easy and fast way to use media and it also saves device memory. Playing media online also saves you from the headache of management of files in the device.
To stream audios, android provides a class MediaPlayer which is used to play online or offline media files in the app.
You can follow the below code segment and the explanation after that to stream the media directly from the URL.
1 2 3 4 5 |
MediaPlayer mediaPlayerOnline = new MediaPlayer(); mediaPlayerOnline.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayerOnline.setDataSource("your_file_url"); mediaPlayerOnline.prepareAsync(); mediaPlayerOnline.start(); |
As you can see in the above code segment that an object of MediaPlayer is created and the url is passed to the function setDataSource().
start() function is used to play the audio file on the URL.
Similarly to play the downloaded audio file. You can follow the below given code segment and the explanation following it.
1 2 3 4 5 |
MediaPlayer mediaPlayerDownloaded = new MediaPlayer(); mediaPlayerDownloaded.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayerDownloaded = MediaPlayer.create(this, Uri.parse(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/" + "your_file_name.mp3")))); mediaPlayerDownloaded.start(); |
This is similar to the playing media online except that you need to create() function and pass the file path to the as the parameter.
To perform some task after the completion of audio. you can use the MediaPlayer.OnCompletionListener() function. Check the code segment below
1 2 3 4 5 6 |
mediaPlayerDownloaded.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { //perform your task } }); |
You can also use the isPlaying function to make a single button for play and pause.
1 2 3 4 5 |
if (mediaPlayerOnline.isPlaying()) { mediaPlayerOnline.pause(); } else { mediaPlayerOnline.start(); } |
Thank you very much, this is Vedesh Kumar signing off.