If you are developing an Android app using Kotlin and facing the issue where MediaPlayer is not playing audio, you are not alone. This is a common problem many developers encounter when handling audio playback. In this article, we will explore the root causes, common mistakes, and provide complete solutions with Kotlin MediaPlayer code examples.
Why MediaPlayer May Not Play Audio in Kotlin
The MediaPlayer
class in Android is powerful, but it also comes with strict requirements. Here are some common reasons why your audio might not play:
- Incorrect file path or URI: The audio file path may be wrong or inaccessible.
- Permission issues: Missing
READ_EXTERNAL_STORAGE
orINTERNET
permission if streaming online audio. - Lifecycle mismanagement: MediaPlayer not properly prepared or released during
Activity
orFragment
lifecycle. - Asynchronous preparation: Forgetting to use
prepareAsync()
with anOnPreparedListener
. - Audio focus: Another app may have audio focus, preventing playback.
Basic Kotlin MediaPlayer Example
Here is a minimal working example to play an audio file stored in the raw
folder:
val mediaPlayer = MediaPlayer.create(this, R.raw.sample_audio) mediaPlayer.start()
While this may work for simple cases, developers often encounter issues when using MediaPlayer
with external files or streaming URLs.
Common Mistake 1: Not Handling Permissions
If you are loading audio from external storage, you need to request runtime permissions:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1) }
Without this permission, your MediaPlayer
will silently fail to play the file.
Common Mistake 2: Wrong Use of prepare()
For streaming audio (e.g., from a URL), you should not use prepare()
directly on the main thread because it blocks the UI. Instead, use prepareAsync()
and implement OnPreparedListener
:
val mediaPlayer = MediaPlayer() mediaPlayer.setDataSource("https://www.example.com/audiofile.mp3") mediaPlayer.setOnPreparedListener { it.start() } mediaPlayer.prepareAsync()
Handling Lifecycle Properly
One of the main reasons Kotlin MediaPlayer not playing audio happens is lifecycle mismanagement. You must release the MediaPlayer
when your activity is destroyed or paused:
override fun onPause() { super.onPause() if (mediaPlayer.isPlaying) { mediaPlayer.pause() } } override fun onDestroy() { super.onDestroy() mediaPlayer.release() }
Complete Example: Playing Online Audio with Controls
Below is a complete example of a Kotlin Activity that streams audio from a URL with Play and Pause buttons:
class MainActivity : AppCompatActivity() { private lateinit var mediaPlayer: MediaPlayer private var isPrepared = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val playButton: Button = findViewById(R.id.playButton) val pauseButton: Button = findViewById(R.id.pauseButton) mediaPlayer = MediaPlayer() mediaPlayer.setDataSource("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3") mediaPlayer.setOnPreparedListener { isPrepared = true it.start() } mediaPlayer.setOnErrorListener { _, what, extra -> Log.e("MediaPlayer", "Error: what=$what extra=$extra") true } mediaPlayer.prepareAsync() playButton.setOnClickListener { if (isPrepared && !mediaPlayer.isPlaying) { mediaPlayer.start() } } pauseButton.setOnClickListener { if (mediaPlayer.isPlaying) { mediaPlayer.pause() } } } override fun onDestroy() { super.onDestroy() if (this::mediaPlayer.isInitialized) { mediaPlayer.release() } } }
Troubleshooting Checklist
If your Kotlin MediaPlayer is not playing audio, go through this checklist:
- Check if the file path or URL is correct.
- Verify storage or internet permissions are granted.
- Use
prepareAsync()
for network streams. - Handle lifecycle with
release()
to avoid resource leaks. - Check for logcat errors with
MediaPlayer
tag.
Conclusion
The MediaPlayer
in Kotlin can sometimes be tricky, but once you understand the common pitfalls, handling audio becomes straightforward. Always remember to manage lifecycle properly, use the right preparation method, and ensure permissions are granted. Following these guidelines will solve most cases where Kotlin MediaPlayer not playing audio.
For more details on MediaPlayer, you can also read the official Android documentation:
MediaPlayer Android Docs.