Android Play Local / URL Audio With ProgressBar Example

This article will show you how to play audio files from local files or web URL files in android programmatically. It also shows how to display audio playing progress in a progress bar.

1. Play Audio In Android Steps.

  1. android.media.MediaPlayer class is used to play android audio files. You should follow the below steps to use it.
  2. Create a new instance of MediaPlayer.
    audioPlayer = new MediaPlayer();
  3. If you want to play music from a web URL, because it is streaming audio then you need to set the audio stream type.
    audioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  4. Call MediaPlayer‘s setDataSource(Uri uri) method to set the audio file URI or path ( local file path or web URL).
    audioPlayer.setDataSource(getApplicationContext(), audioFileUri);
  5. Call the MediaPlayer object’s prepare() method to prepare.
  6. Call the MediaPlayer object’s start, pause, stop, release, seekTo, isPlaying, getDuration method as you need.
  7. When the activity is destroyed, do not forget to release the MediaPlayer object by it’s release method.
  8. You should declare the below permissions in the AndroidManifest.xml file to play local or URL audio. Otherwise, java.io.IOException may be thrown.
    <!-- Play local audio file required permission.-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
    <!-- Play web url audio file required permission.-->
    <uses-permission android:name="android.permission.INTERNET" />

2. Show Audio Progress While Playing.

  1. Use android.widget.ProgressBar component to display audio file playing progress.
  2. To do this, you need to create an android.os.Handler object in activity main thread, it’s responsibility is to listen to the main thread message queue and pick up the update-progress ( child thread sent ) messages. Then update the progress bar as required.
  3. Because Android does not allow update UI control in child thread directly, so we have to create a child thread that sends an update-progress message to the main thread message queue every one second.
  4. Then every one second, the progress bar handler in the activity main thread will get a message from the child thread and then update the audio progress bar as needed.

3. Play Android Audio Example.

3.1 Play local audio file example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/VFecRoR5DmM

  1. The above video shows an example that plays a local audio file on an Android emulator.
  2. First, you need to use the android device monitor to push the mp3 file into the android emulator. You can read the article Android Device Monitor Cannot Open Data Folder Resolve Method to learn more.
  3. If you can not open the folder ( where you want to save the mp3 file such as /storage/emulated/0/Music) in the android device monitor, run the command adb root in dos window, then you get root permission to upload the mp3 file to the folder.

3.2 Play web URL audio file example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/1KIPBYxHIm0

4. Main Activity Java File.

  1. PlayAudioActivity.java
    package com.dev2qa.example.audio;
    
    import android.Manifest;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.media.AudioManager;
    import android.media.MediaPlayer;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.support.annotation.NonNull;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.text.TextUtils;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ProgressBar;
    import android.widget.Toast;
    
    import com.dev2qa.example.R;
    
    import java.io.IOException;
    
    public class PlayAudioActivity extends AppCompatActivity {
    
        // User input mp3 file url in this text box. Or display user selected mp3 file name.
        private EditText audioFilePathEditor;
    
        // Click this button to let user select mp3 file.
        private Button browseAudioFileButton;
    
        // Start play audio button.
        private Button startButton;
    
        // Pause playing audio button.
        private Button pauseButton;
    
        // Stop playing audio button.
        private Button stopButton;
    
        // Show played audio progress.
        private ProgressBar playAudioProgress;
    
        // Used when user select audio file.
        private static final int REQUEST_CODE_SELECT_AUDIO_FILE = 1;
    
        // Used when user require android READ_EXTERNAL_PERMISSION.
        private static final int REQUEST_CODE_READ_EXTERNAL_PERMISSION = 2;
    
        // Used when update audio progress thread send message to progress bar handler.
        private static final int UPDATE_AUDIO_PROGRESS_BAR = 3;
    
        // Used to control audio (start, pause , stop etc).
        private MediaPlayer audioPlayer = null;
    
        // Save user selected or inputted audio file unique resource identifier.
        private Uri audioFileUri = null;
    
        // Used to distinguish log data.
        public static final String TAG_PLAY_AUDIO = "PLAY_AUDIO";
    
        // Wait update audio progress thread sent message, then update audio play progress.
        private Handler audioProgressHandler = null;
    
        // The thread that send message to audio progress handler to update progress every one second.
        private Thread updateAudioPalyerProgressThread = null;
    
        // Record whether audio is playing or not.
        private boolean audioIsPlaying = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_play_audio);
    
            setTitle("dev2qa.com - Android Play Audio Example.");
    
            startButton = (Button)findViewById(R.id.play_audio_start_button);
    
            pauseButton = (Button)findViewById(R.id.play_audio_pause_button);
    
            stopButton = (Button)findViewById(R.id.play_audio_stop_button);
    
            playAudioProgress = (ProgressBar)findViewById(R.id.play_audio_progressbar);
    
            /* Initialize audio progress handler. */
            if(audioProgressHandler==null) {
                audioProgressHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (msg.what == UPDATE_AUDIO_PROGRESS_BAR) {
    
                            if(audioPlayer!=null) {
                                // Get current play time.
                                int currPlayPosition = audioPlayer.getCurrentPosition();
    
                                // Get total play time.
                                int totalTime = audioPlayer.getDuration();
    
                                // Calculate the percentage.
                                int currProgress = (currPlayPosition * 1000) / totalTime;
    
                                // Update progressbar.
                                playAudioProgress.setProgress(currProgress);
                            }
                        }
                    }
                };
            }
    
            /* When user input key up in this text editor. */
            audioFilePathEditor = (EditText)findViewById(R.id.play_audio_file_path_editor);
            audioFilePathEditor.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View view, int i, KeyEvent keyEvent) {
                    int action = keyEvent.getAction();
                    if(action == KeyEvent.ACTION_UP) {
                        String text = audioFilePathEditor.getText().toString();
                        if (text.length() > 0) {
                            startButton.setEnabled(true);
                            pauseButton.setEnabled(false);
                            stopButton.setEnabled(false);
                        } else {
                            startButton.setEnabled(false);
                            pauseButton.setEnabled(false);
                            stopButton.setEnabled(false);
                        }
                    }
                    return false;
                }
            });
    
    
            /* Click this button to popup select audio file component. */
            browseAudioFileButton = (Button)findViewById(R.id.play_audio_browse_audio_file_button);
            browseAudioFileButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Require read external storage permission from user.
                    int readExternalStoragePermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE);
                    if(readExternalStoragePermission != PackageManager.PERMISSION_GRANTED)
                    {
                        String requirePermission[] = {Manifest.permission.READ_EXTERNAL_STORAGE};
                        ActivityCompat.requestPermissions(PlayAudioActivity.this, requirePermission, REQUEST_CODE_READ_EXTERNAL_PERMISSION);
                    }else {
                        selectAudioFile();
                    }
                }
            });
    
            // When start button is clicked.
            startButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    startButton.setEnabled(false);
    
                    pauseButton.setEnabled(true);
    
                    stopButton.setEnabled(true);
    
                    String audioFilePath = audioFilePathEditor.getText().toString();
                    if(!TextUtils.isEmpty(audioFilePath)) {
    
                        stopCurrentPlayAudio();
    
                        initAudioPlayer();
    
                        audioPlayer.start();
    
                        audioIsPlaying = true;
    
                        // Display progressbar.
                        playAudioProgress.setVisibility(ProgressBar.VISIBLE);
    
                        if(updateAudioPalyerProgressThread == null) {
    
                            // Create the thread.
                            updateAudioPalyerProgressThread = new Thread() {
                                @Override
                                public void run() {
                                    try {
                                        while (audioIsPlaying) {
    
                                            if (audioProgressHandler != null) {
                                                // Send update audio player progress message to main thread message queue.
                                                Message msg = new Message();
                                                msg.what = UPDATE_AUDIO_PROGRESS_BAR;
                                                audioProgressHandler.sendMessage(msg);
    
                                                Thread.sleep(1000);
                                            }
                                        }
                                    } catch (InterruptedException ex) {
                                        Log.e(TAG_PLAY_AUDIO, ex.getMessage(), ex);
                                    }
                                }
                            };
                            updateAudioPalyerProgressThread.start();
                        }
                    }else
                    {
                       Toast.makeText(getApplicationContext(), "Please specify an audio file to play.", Toast.LENGTH_LONG).show();
                    }
                }
            });
    
            /* When pause button is clicked. */
            pauseButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(audioIsPlaying)
                    {
                        audioPlayer.pause();
                        startButton.setEnabled(true);
                        pauseButton.setEnabled(false);
                        stopButton.setEnabled(true);
    
                        audioIsPlaying = false;
    
                        updateAudioPalyerProgressThread = null;
                    }
                }
            });
    
            /* When stop button is clicked. */
            stopButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(audioIsPlaying)
                    {
                        audioPlayer.stop();
                        audioPlayer.release();
                        audioPlayer = null;
                        startButton.setEnabled(true);
                        pauseButton.setEnabled(false);
                        stopButton.setEnabled(false);
    
                        updateAudioPalyerProgressThread = null;
                        playAudioProgress.setProgress(0);
                        playAudioProgress.setVisibility(ProgressBar.INVISIBLE);
    
                        audioIsPlaying = false;
                    }
                }
            });
    
        }
    
        /* Initialize media player. */
        private void initAudioPlayer()
        {
            try {
                if(audioPlayer == null)
                {
                    audioPlayer = new MediaPlayer();
    
                    String audioFilePath = audioFilePathEditor.getText().toString().trim();
    
                    Log.d(TAG_PLAY_AUDIO, audioFilePath);
    
                    if(audioFilePath.toLowerCase().startsWith("http://"))
                    {
                        // Web audio from a url is stream music.
                        audioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        // Play audio from a url.
                        audioPlayer.setDataSource(audioFilePath);
                    }else
                    {
                        if(audioFileUri != null)
                        {
                            // Play audio from selected local file.
                            audioPlayer.setDataSource(getApplicationContext(), audioFileUri);
                        }
                    }
                    audioPlayer.prepare();
                }
            }catch(IOException ex)
            {
                Log.e(TAG_PLAY_AUDIO, ex.getMessage(), ex);
            }
        }
    
        /* This method start get content activity to let user select audio file from local directory.*/
        private void selectAudioFile()
        {
            // Create an intent with ACTION_GET_CONTENT.
            Intent selectAudioIntent = new Intent(Intent.ACTION_GET_CONTENT);
    
            // Show audio in the content browser.
            // Set selectAudioIntent.setType("*/*") to select all data
            // Intent for this action must set content type, otherwise android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.GET_CONTENT } will be thrown
            selectAudioIntent.setType("audio/*");
    
            // Start the activity.
            startActivityForResult(selectAudioIntent, REQUEST_CODE_SELECT_AUDIO_FILE);
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if(requestCode == REQUEST_CODE_SELECT_AUDIO_FILE)
            {
                if(resultCode==RESULT_OK)
                {
                    // To make example simple and clear, we only choose audio file from
                    // local file, this is easy to get audio file real local path.
                    // If you want to get audio file real local path from a audio content provider
                    // Please read another article.
                    audioFileUri = data.getData();
                    String audioFileName = audioFileUri.getLastPathSegment();
    
                    audioFilePathEditor.setText("You selected audio file is " + audioFileName);
    
                    initAudioPlayer();
    
                    startButton.setEnabled(true);
    
                    pauseButton.setEnabled(false);
    
                    stopButton.setEnabled(false);
                }
            }
        }
    
        /* Stop current play audio before play another. */
        private void stopCurrentPlayAudio()
        {
            if(audioPlayer!=null && audioPlayer.isPlaying())
            {
                audioPlayer.stop();
                audioPlayer.release();
                audioPlayer = null;
            }
        }
    
        /* This method will be called after user choose grant read external storage permission or not. */
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            if(requestCode==REQUEST_CODE_READ_EXTERNAL_PERMISSION)
            {
                if(grantResults.length > 0)
                {
                    int grantResult = grantResults[0];
                    if(grantResult == PackageManager.PERMISSION_GRANTED)
                    {
                        // If user grant the permission then open browser let user select audio file.
                        selectAudioFile();
                    }else
                    {
                        Toast.makeText(getApplicationContext(), "You denied read external storage permission.", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    
        @Override
        protected void onDestroy() {
            if(audioPlayer!=null)
            {
                if(audioPlayer.isPlaying())
                {
                    audioPlayer.stop();
                }
    
                audioPlayer.release();
                audioPlayer = null;
            }
    
            super.onDestroy();
        }
    }

5. Layout XML File.

  1. activity_play_audio.xml
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <EditText
            android:id="@+id/play_audio_file_path_editor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Browse an audio file path or input a audio file url."/>
    
        <Button
            android:id="@+id/play_audio_browse_audio_file_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Browse Audio File"/>
    
        <Button
            android:id="@+id/play_audio_start_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Start"
            android:enabled="false"/>
    
        <Button
            android:id="@+id/play_audio_pause_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Pause"
            android:enabled="false"/>
    
        <Button
            android:id="@+id/play_audio_stop_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Stop"
            android:enabled="false"/>
    
    
        <ProgressBar
            android:id="@+id/play_audio_progressbar"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:max="100"
            android:visibility="invisible"/>
    
    
    </LinearLayout>

6. Android Manifest XML File.

  1. AndroidManifest.xml
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dev2qa.example">
    
        <!-- Play local audio file required permission.-->
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
        <!-- Play web url audio file required permission.-->
        <uses-permission android:name="android.permission.INTERNET" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            
            <activity android:name=".audio.PlayAudioActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.