Step-by-Step Guide: Creating an Audio Player for Android using MediaPlayer and SeekBar

Explore in our latest blog post how to develop a user-friendly audio player for Android using MediaPlayer and SeekBar. Learn step by step how to implement play/stop functions and dynamically change the song position. Dive into the world of Android development and take your music apps to the next level!

Android MediaPlayer

The MediaPlayer class is used for playing audio and video files. The commonly used methods of the MediaPlayer class are:

  • start()
  • stop()
  • release() – To avoid memory leaks.
  • seekTo(position) – This is used with the SeekBar.
  • isPlaying() – Indicates whether the song is playing or not.
  • getDuration() – Used to get the total duration, which helps determine the upper limit of our SeekBar. This function returns the duration in milliseconds.
  • setDataSource(FileDescriptor fd) – Used to set the file to be played.
  • setVolume(float leftVolume, float rightVolume) – Used to set the volume level. The value is a float number between 0 and 1.

Project Structure

We need three things to create an application that plays audio and allows you to change the position of the current song track:

  • MediaPlayer
  • SeekBar with Text – To display the current progress time next to the thumb.
  • Runnable Thread – To update the SeekBar.

Conclusion

By clicking on the FloatingActionButton, the playSong function is triggered, where we pause the song and reset the MediaPlayer. Once mediaPlayer.prepare() is called, the song details are available. We can now get the duration and set it to the maximum position of the SeekBar. Setting setLooping to false prevents the song from playing infinitely until the user stops it. We start the thread that triggers the run method, which is part of the Runnable interface we implemented. Within the run method, we update the progress every second, triggering the onProgressChanged method of the SeekBar listener. When the user stops dragging the SeekBar, onStopTrackingTouch is triggered, where we update the song position on the MediaPlayer instance with the seekTo method. Once the song is completed, we reset the position of the SeekBar and release the MediaPlayer instance.

Closing Words

This tutorial demonstrates how to implement a simple audio player in your Android application. You can download the project from GitHub and play the song yourself.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

centron Managed Cloud Hosting in Deutschland

Hibernate SessionFactory

JavaScript, Tutorial
Hibernate SessionFactory Hibernate SessionFactory is the factory class through which we get sessions and perform database operations. Content1 Hibernate SessionFactory2 Conclusion Hibernate SessionFactory Hibernate SessionFactory provides three methods through which…