Android Getting Started tutorial | Android MediaPlayer playing audio

Posted by NArc0t1c on Mon, 13 Dec 2021 05:59:31 +0100

How MediaPlayer is used

Create MediaPlayer

You can directly create new MediaPlayer or use the Create method provided by MediaPlayer.

mediaPlayer = new MediaPlayer();

After the create method is successfully used, the mediaPlayer is in the Prepared state. You can start playing directly.

    mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.fromFile(file));
    mediaPlayer.start();

Set sound source - setDataSource

Set the sound source by calling setDataSource. setDataSource has multiple overloaded methods. Let's look at several commonly used methods.

For example, set and use the resources in assets. try catch may be required in actual situations.

    AssetFileDescriptor fd = null;
    MediaPlayer mediaPlayer = new MediaPlayer();
    fd = context.getApplicationContext().getAssets().openFd(name);
    mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());

Local file, the absolute path of the file is required.

mediaPlayer.setDataSource(file.getAbsolutePath());

Or get the Uri of the file to create a mediaPlayer.

mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.fromFile(file));

To set the network audio, use the setDataSource method to set the url.

mediaPlayer.setDataSource("https://demo.com/sample.mp3"));

When playing network audio, if http is used, an error may be reported

java.io.IOException: Cleartext HTTP traffic to demo.com not permitted

You can simply set the manifest and set usesclleartexttraffic = "true"

<application
        android:usesCleartextTraffic="true">

Prepare - prepare

Prepare audio resources synchronously and asynchronously. prepareAsync() is asynchronous, and prepare is synchronous. Pay attention to thread scheduling and do not block UI threads.

Prepare audio asynchronously, often with mediaplayer Onpreparedlistener works with listeners. Other settings can also be made during asynchronous preparation.

    mediaPlayer.prepareAsync();
    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mediaPlayer.start(); // Play when you're ready
        }
    });

Looping - looping

Set looping setLooping.

mediaPlayer.setLooping(true);

After playing, the OnCompletionListener will not be called back, but the current audio will be played from the beginning.

Play - start

Play the audio and call the start method.

mediaPlayer.start();

When in the Prepared, Pause and PlaybackComplete States, you can call the start method to enter the Started state.

Pause - pause

Pause playback and use the pause method. Before pausing, check whether the mediaPlayer is playing.

    if (mediaPlayer.isPlaying()) {
        mediaPlayer.pause();
    }

If the pause is successful, it is in the Paused state.

Stop - stop

Reviewing the diagram of MediaPlayer state switching, we can know that in the three states of playing, pause and completion, you can call the stop method to enter the Stopped state.

mediaPlayer.stop();

Progress adjustment - seekTo

Adjust playback progress. We usually use music playing software, which generally has this function. The seekTo method accepts a millisecond parameter.

    int targetMS = (int) (percent * mediaPlayer.getDuration());
    mediaPlayer.seekTo(targetMS);

seekTo does not change the state of MediaPlayer.

Reset - reset

The mediaPlayer after reset enters the Idle state. You need to reset the sound source and prepare.

Release - release

When the mediaPlayer is no longer used, it should be released as soon as possible to release relevant resources. After calling release, mediaPlayer enters the End state. At this point, the mediaPlayer can no longer be used.

Common listener

Buffer listener OnBufferingUpdateListener

For example, when we load network audio, we often use this listener to monitor the buffer progress. Displaying the buffer progress can also improve the user experience.

    mMediaPlayer.prepareAsync();
    mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            // percent represents the buffer percentage
        }
    });

Error listener OnErrorListener

mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
        return true; // Returning true indicates that the error is processed here and onCompletion will not be called back
    }
});

Note the return value of onError. You can choose to handle the error yourself.

         * @return True if the method handled the error, false if it didn't.
         * Returning false, or not having an OnErrorListener at all, will
         * cause the OnCompletionListener to be called.
         */
        boolean onError(MediaPlayer mp, int what, int extra);

Completion listener OnCompletionListener

mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        // Play complete
    }
});

Use example

Play the audio in assets

Play the audio files in assets and use the AssetFileDescriptor class. Remember to close AssetFileDescriptor after use.

    private void playAssetsAudio(final String name, Context context) {
        Log.d(TAG, "playAssetWordSound: try to play assets sound file. -> " + name);
        AssetFileDescriptor fd = null;
        try {
            MediaPlayer mediaPlayer;
            Log.v(TAG, "Looking in assets.");
            fd = context.getApplicationContext().getAssets().openFd(name);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.reset();
            mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    Log.d(TAG, "onPrepared: " + name);
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                    Log.d(TAG, "onCompletion: " + name);
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int i, int i1) {
                    mp.release();
                    return true;
                }
            });
        } catch (Exception e) {
            try {
                if (fd != null) {
                    fd.close();
                }
            } catch (Exception e1) {
                Log.e(TAG, "Exception close fd: ", e1);
            }
        } finally {
            if (fd != null) {
                try {
                    fd.close();
                } catch (IOException e) {
                    Log.e(TAG, "Finally, close fd ", e);
                }
            }
        }
    }

Play local audio files

Try playing an audio file. Play only once.

    private void playAudioFile(final File file) {
        Log.d(TAG, "playAudioFile: " + file.getAbsolutePath());
        MediaPlayer mediaPlayer;
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setLooping(false);
            mediaPlayer.setDataSource(file.getAbsolutePath());
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    Log.d(TAG, "Play local sound onError: " + i + ", " + i1);
                    return true;
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "playAudioFile: ", e);
        }
    }

Play online audio

Set url to play online audio

    private void playOnlineSound(String soundUrlDict) {
        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(soundUrlDict);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (mp != null) {
                        mp.release();
                    }
                    Log.d(TAG, "onCompletion: play sound.");
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    Log.d(TAG, "Play online sound onError: " + i + ", " + i1);
                    return false;
                }
            });
        } catch (IOException e1) {
            Log.e(TAG, "url: ", e1);
        }
    }

[Android audio and video development series tutorials]

Topics: Android