android-studio
  1. android-studio-mediaplayer-audio

Android Studio MediaPlayer: Audio

Syntax

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

Example

MediaPlayer mediaPlayer;
TextView playerStatus;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mediaPlayer = MediaPlayer.create(this, R.raw.my_audio_file);
    playerStatus = (TextView) findViewById(R.id.player_status);

    // Play audio file
    mediaPlayer.start();

    // Set the player status text
    playerStatus.setText("Playing audio file.");
}

@Override
protected void onStop() {
    super.onStop();
    mediaPlayer.stop();
    mediaPlayer.release();
}

Output

The output of the above code will be the playing of the audio file specified in the create() method. The player status text will also update to show that the audio file is currently playing.

Explanation

The MediaPlayer class is used to control playback of audio and video files. The create() method is used to create a new MediaPlayer object and specify the audio file to play. The start() method is then used to start the playback of the audio file.

In the example above, we create a new MediaPlayer object in the onCreate() method and specify the audio file to play. We also create a TextView object to display the player status. We then start the playback of the audio file and update the player status text to reflect that the audio file is playing.

Finally, we ensure that the MediaPlayer is stopped and released when the activity is stopped using the onStop() method. This is important to avoid memory leaks in your application.

Use

The MediaPlayer class can be used to add audio playback functionality to your Android applications. This can be useful for playing music or sound effects in your app.

Important Points

  • The create() method is used to create a new MediaPlayer object and specify the audio file to play.
  • The start() method is used to start the playback of the audio file.
  • The MediaPlayer should be stopped and released when the activity is stopped to avoid memory leaks.

Summary

In this tutorial, we looked at how to use the MediaPlayer class to play audio files in your Android applications. We covered the syntax, example, output, explanation, use, important points, and summary of the MediaPlayer class.

Published on: