info@androidpaper.co.in

Android MediaPlayer with Examples

The MediaPlayer class in Android provides a flexible framework for playing audio and video files. It allows you to handle various media-related operations such as playing, pausing, seeking, and controlling the playback of media files.

To use the MediaPlayer to play an audio file from the raw folder in Android, you can follow these steps:
Place your audio file in the raw folder:
Create a folder named "raw" under the "res" directory of your Android project. Copy the audio file into the "raw" folder.

Import the required classes:
Declare a MediaPlayer object:

import android.media.MediaPlayer;

private MediaPlayer mediaPlayer;

Initialize the MediaPlayer:

mediaPlayer = MediaPlayer.create(context, R.raw.your_audio_file);

Replace your_audio_file with the name of your audio file without the file extension. For example, if your audio file is named "audio.mp3", you would use R.raw.audio.
Set up MediaPlayer listeners and start playback:

mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        // The MediaPlayer is prepared and ready to play
        mediaPlayer.start();
    }
});

Release the MediaPlayer:
To release the resources used by the MediaPlayer when you're done playing the audio, call the release() method

mediaPlayer.release();

Stop the MediaPlayer:
To stopthe resources used by the MediaPlayer when you're done playing the audio, call the stop() method:

mediaPlayer.stop();

Another Written Description

This is a basic overview of using the MediaPlayer to play an audio file from the raw folder in Android using Java. Make sure to replace your_audio_file with the appropriate file name, and handle exceptions and error scenarios based on your app's needs.