我想创造一种音景。为此,我有一个服务,其中创建了三个MediaPlayer实例。完成后,他们应选择一个新文件进行播放,播放该文件并重复该过程。
以下代码仅播放来自.create()
的文件,但似乎没有做任何其他事情。在运行时,打印“selectstarted”和“playstarted”,所以我只能猜测错误是在selectBordun()
或play()
函数中的某个地方,但我不知道在哪里。
请注意,我已缩短代码的可读性。每次都提到mPlayer
,我有两次相同的代码,只有mPlayer2
和mPlayer3
。但基本原则应该与一个实例相同。
open class BordunService : Service() {
private lateinit var mPlayer: MediaPlayer
override fun onCreate() {
mPlayer = MediaPlayer.create(this, R.raw.fping)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
if (intent.hasExtra("Play")) {
playBordun()
}
}
private fun playBordun() {
fun playMPlayer() {
mPlayer.setOnCompletionListener(object: MediaPlayer.OnCompletionListener {
override fun onCompletion(p0: MediaPlayer?) {
println("completem")
selectBordun(mPlayer)
}
})
mPlayer.setOnPreparedListener(object:MediaPlayer.OnPreparedListener {
override fun onPrepared(p0: MediaPlayer?) {
println("preparedm")
mPlayer.start()
}
})
}
GlobalScope.launch {
playMPlayer()
}
}
fun selectBordun(player: MediaPlayer) {
println("selectstarted")
player.reset()
val randomGenerator = Random()
val bordunInt = randomGenerator.nextInt(3) + 1
when (bordunInt) {
1 -> {
val afd = this.getResources().openRawResourceFd(R.raw.cping)
afd.close()
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength())
// player.prepareAsync()
play(player)
}
2 -> {
val afd = this.getResources().openRawResourceFd(R.raw.ebping)
afd.close()
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength())
// player.prepareAsync()
play(player)
}
3 -> {
val afd = this.getResources().openRawResourceFd(R.raw.gping)
afd.close()
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength())
// player.prepareAsync()
play(player)
}
}
}
fun play(player: MediaPlayer) {
println("playstarted")
player.setOnPreparedListener(object:MediaPlayer.OnPreparedListener {
override fun onPrepared(p0: MediaPlayer?) {
println("preparedplayer")
player.start()
}
})
player.setOnCompletionListener(object: MediaPlayer.OnCompletionListener {
override fun onCompletion(p0: MediaPlayer?) {
println("completeplayer")
selectBordun(player)
}
})
}
}
好吧,我使用更多样板代码解决了这个问题,使用自己的函数释放并重新创建每个MediaPlayer实例,因此我不必设置新的数据源。