How to play local audio files using Media Player | Android

9Qv7...HJpG
13 Feb 2024
41


Hellooo guys ✌ Today I want to talk about how to play local audio files using Media Player in Android. Imagine we have audio files and want to play them in our Android application. So, I want to answer the following questions.

  • What is the raw file?
  • What is the MediaPlayer in Android?
  • What are the actions of the Media Player and how to use it?

Let’s explain them with code examples.

What is the raw file?

Raw files can contain any type of data, such as audio, video, images, or text, that needs to be included with the app. So, we have local audio files; adding them to the raw file would be great. That’s why we are using the Media Player class to play them. Let me show you how to create it and using in Android Studio.
Step 1 → Add a raw file under the resource package


Step 2 → Create a new resource directory called raw or whatever you want. Then click ok.


Step 3 → Add some mp3 files to play that you want.


Now our environment is ready to play them. We can move to the next step.

What is the MediaPlayer in Android?


The Android multimedia framework includes support for playing a variety of common media types so that you can easily integrate audio, video, and images into your applications. You can play audio or video from media files stored in your application’s resources (raw resources), from standalone files in the filesystem, or from a data stream arriving over a network connection, all using MediaPlayer APIs. You can learn everything about Media Player by following this link.

MediaPlayer overview | Android Developers
Get one of our Figma kits for Android or Material Design and start designing your app's UI today.developer.android.com

Now we can build our app. We have learned about Raw and introduced MediaPlayer.

What are the actions of the Media Player and how to use it?


We should know some topics before starting development. We are now ready to use a media player in our application. I need to explain some concepts with code samples. These will be the permissions, prepare, release, start, stop, resume, forward, backward, and destroy of the media player object. At the same time, we will have to take some precautions about the media player running in the background.

Step 1 → Manifest declarations.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Internet Permission — If you are using MediaPlayer to stream network-based content, your application must request network access.

Wake Lock Permission — If your player application needs to keep the screen from dimming or the processor from sleeping, or uses the MediaPlayer.setScreenOnWhilePlaying() or MediaPlayer.setWakeMode() methods, you must request this permission.

Step 2 → Create a media player object, call other functions, and check the state of sound.

playButton.setOnClickListener {
    song?.let {
        if(mediaPlayer == null){
            mediaPlayer = MediaPlayer.create(requireContext(), it)
            initialSeekBar()
        }
    }
    isPlaying = if (!isPlaying) {
        startSong()
        true
    } else {
        pauseSong()
        false
    }
}


Step 3 → Create a function that starts the media player object.

private fun startSong() {
    with(binding) {
        playButton.setImageResource(R.drawable.pause_song)
        mediaPlayer?.start()
    }
}


Step 4 → Create a function that pauses the media player object.

private fun pauseSong() {
    with(binding) {
        playButton.setImageResource(R.drawable.play_icon)
        mediaPlayer?.pause()
    }
}


Step 5 → Set the audio file to forward 15 seconds using seekTo() command.

forwardButton.setOnClickListener {
    mediaPlayer?.let {
        currentPosition = it.currentPosition
        var duration = it.duration
        if (it.isPlaying && duration != currentPosition) {
            currentPosition += 15000
            it.seekTo(currentPosition)
        }
    }
}


Step 6 → Set the audio file to backward 15 seconds using seekTo() command.

backwardButton.setOnClickListener {
    mediaPlayer?.let {
        currentPosition = it.currentPosition
        var duration = it.duration
        if (it.isPlaying && duration != currentPosition) {
            currentPosition -= 15000
            it.seekTo(currentPosition)
        }
    }
}


Step 7 → Create a setOnSeekBarChangeListener() to change and control the seek bar progress.

seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
    override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
        if(p2) mediaPlayer?.seekTo(p1)
    }
    override fun onStartTrackingTouch(p0: SeekBar?) = Unit

    override fun onStopTrackingTouch(p0: SeekBar?) = Unit

})


Step 8 → Create a function called initialSeekBar().

private fun initialSeekBar(){
    with(binding){
        mediaPlayer?.let {
            seekBar.max = it.duration
        }
        val handler = Handler()
        handler.postDelayed(object: Runnable {
            override fun run() {
                try {
                    mediaPlayer?.let {
                        seekBar.progress = it.currentPosition
                    }
                    handler.postDelayed(this,300)
                }catch (e:Exception){
                    seekBar.progress = 0
                }
            }
        },0)
    }
}


Step 9 → Reset the MediaPlayer object when the fragment is destroyed.

override fun onAttach(context: Context) {
        super.onAttach(context)
        val callBack: OnBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                findNavController().popBackStack()
                mediaPlayer?.reset()
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(this, callBack)
    }


That’s it. Now let’s see how our application works.

I hope you like it 😃 Please let me know if there are any areas you see missing or want me to edit.
Have a good day all of you guys ✌.

Get fast shipping, movies & more with Amazon Prime

Start free trial

Enjoy this blog? Subscribe to yusufyildiz41

0 Comments