I am trying to build an Android app (coded in Kotlin) which plays a random sound file and after it's done, plays another random file and so on. With the current version of the code it seems that more than one files are played at the same time, instead of waiting the previous one to finish.
In the commented lines in my code I tried implementing a countdown timer for each playing of a music file. It results in the following: when I start the app oly one file is played and then it stops (possibly crashes)
class MainActivity : AppCompatActivity() {
fun playSound(running:Int) {
var completition=1
while (running==1 && completition==1) {
completition=0
var rnds = Random.nextInt(0..1)
if (rnds==1 ) {
val mMediaPlayer = MediaPlayer.create(this, R.raw.right)
mMediaPlayer!!.isLooping = false
mMediaPlayer!!.start()
mMediaPlayer!!.setOnCompletionListener { completition=1 }
}
if (rnds==0 ) {val mMediaPlayer = MediaPlayer.create(this, R.raw.left)
mMediaPlayer!!.isLooping = false
mMediaPlayer!!.start()
mMediaPlayer!!.setOnCompletionListener { completition=1 }
}
}
}
fun music(){
var i=1
while(i==1) {
i=0
val random=(0..1).random()
if (random==1){
val refMediaPlayer=MediaPlayer.create(this,R.raw.right)
refMediaPlayer!!.isLooping = false
refMediaPlayer!!.start()
//object :CountDownTimer(1000,100) {
//override fun onTick(p0: Long) {
// TODO("Not yet implemented")
// }
//override fun onFinish() {
//i=1
//}
// }.start();
}
if (random==0){
val refMediaPlayer=MediaPlayer.create(this,R.raw.left)
refMediaPlayer!!.isLooping = false
refMediaPlayer!!.start()
// object :CountDownTimer(1000,100) {
//override fun onTick(p0: Long) {
// TODO("Not yet implemented")
// }
// override fun onFinish() {
// i=1
// }
//}.start();
}
}
}
// 4. Destroys the MediaPlayer instance when the app is closed
// override fun onStop() {
// super.onStop()
// if (mMediaPlayer != null) {
// mMediaPlayer!!.release()
// mMediaPlayer = null
// }
//}
override fun onCreate(savedInstanceState: Bundle?) {
val running=1
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
music()
}
}
I had a similar problem in an application I built. I ended up putting all the sound stuff on a separate thread and pausing the thread for the duration of each audio file. So something like:
The sound will keep playing, but the code's execution will be paused for the amount of time you specify.
I'm not sure of the exact syntax for Kotlin because I use Java.