I'm trying to play a .mp3
background for an activity but the audio only lasts 2 or 3 seconds and stops when it actually .mp3
lasts 1 min 3 seg
. Why does this happen?
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mp = MediaPlayer.create(this, R.raw.suspenso)
mp.setVolume(100F, 100F)
mp.start()
}
For what you describe "it lasts 2 or 3 seconds and stops", if the playback does not finish, the problem is surely the audio file, it probably has an error , specifically you must ensure that it uses the appropriate codecs
Android: Supported Formats
To check specifically what the error is, I suggest you use the listener
OnErrorListener
, where you can print and check what type of error you get when an error occurs.I also suggest you also use the listener
OnCompletionListener
, which will tell you when I have completely finished playing the media file.Kotlin: How to play audio using MediaPlayer?
After searching and trying several examples I have found the solution.
If you look at my code, the initialization of
MediaPlayer
is inside theonCreate
. Big mistake!The solution is the next: