Android Play Local / URL Audio With ProgressBar Example

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

1. Play Audio In Android Steps.

android.media.MediaPlayer class is used to play android audio file. You should follow below steps to use it.

  1. Create a new instance of MediaPlayer.
    audioPlayer = new MediaPlayer();
  2. If play a music from web url, because it is a stream audio then you need set it’s streamType.
    audioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  3. 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);
  4. Call MediaPlayer’s prepare() method to prepare.
  5. Call it’s start, pause, stop, release, seekTo, isPlaying, getDuration method as you need.
  6. When the activity is destroyed, do not forget release the MediaPlayer object by it’s release method.
  7. You should declare below permissions in 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.

Use android.widget.ProgressBar component to display audio file playing progress. To do this, you need to create a android.os.Handler object in activity main thread, it’s responsibility is to listen to main thread message queue and pick up update-progress-thread ( child thread ) sent messages. Then update the progress bar as required.

Because android do not allow update UI control in child thread directly, so we have to create a child thread which send update progressbar message to main thread message queue every one second.

Then every one second, progressbar handler in activity main thread will get a message from the child thread and then update the audio progressbar as needed.

3. Play Android Audio Example.

Play local audio file example.

android play local audio file example

First you need to push the mp3 file into android emulator use android device monitor as below. You can read article Android Device Monitor Cannot Open Data Folder Resolve Method to learn more.

If you can not open below folder in android device monitor, run command adb root in dos window, then you get root permission.

push audio file into app external storage folder use android device monitor

Play web url audio file example.

android play web url audio file example

4. Main Activity Java File.

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.

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.

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>
(Visited 674 times, 6 visits today)
READ :   How To Invoke Custom Content Provider In Other Apps Examples

Leave a Reply

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