kotlin 如何使用Android MediaPlayer类循环播放声音

k4ymrczo  于 11个月前  发布在  Kotlin
关注(0)|答案(1)|浏览(168)

我正在制作一个节拍器应用程序。这意味着我需要循环播放一个声音几次,然后每隔一定次数播放另一个声音。我的第一个循环播放声音的方法如下:

fun startMetronome(){
    isPlaying = true
    upbeat = MediaPlayer.create(this, R.raw.upbeat)
    CoroutineScope(Dispatchers.IO).launch {
        while(isPlaying) {
            for(i in 0..5){continue}
                upbeat?.start()
                Thread.sleep(500)
        }
    }
}

字符串
问题是这会导致循环每隔几个滴答就随机挂起。解决方案是移动upbeat变量的赋值:

fun startMetronome(){
    isPlaying = true
    CoroutineScope(Dispatchers.IO).launch {
        while(isPlaying) {
            for(i in 0..5){continue}
                //moved it here
                upbeat = MediaPlayer.create(this, R.raw.upbeat)
                upbeat?.start()
                Thread.sleep(500)
        }
    }
}


但是另一方面,当循环在CoroutineScope中时,它会抛出一个错误,我需要它,因为我希望能够播放和停止循环。如果你们中有人知道正确的方法,请告诉我。

p1tboqfb

p1tboqfb1#

你可以尝试使用VideoView
1.如果使用XML定义,
2)在你的代码中,让我们说你正在使用Fragment,然后像这样定义函数:

fun startPlaying() {
val uri = Uri.parse("fileorhttps://YourVideoURL")
        videoView.setVideoURI(uri)
        videoView.requestFocus()
        videoView.setOnPreparedListener { it.isLooping = false }
        //Below is completion listener which will trigger when your video file playing completed.
        videoView.setOnCompletionListener {  
         //Can also add delay here if you want before playing
        startPlaying()//here you can call it as long as you want up to infinite number of times
}

字符串

相关问题