我尝试连续播放一个简短的.mp3声音(哔哔声),每分钟100次。它正确地播放了大约30-45次(在新设备上更多),然后它停止了一段时间(约30秒),然后再次播放(仅约10次)。
我尝试了两种方法 SoundPool
(playBeepSound1
)和 MediaPlayer
(playBeepSound2
)所以也许我用的是 Handler
错。
private val delay: Float = 60.0F / 100.0F * 1000.0F // 100 times per minute
private var handler: Handler? = null
private var soundPool: SoundPool? = null
private var mediaPlayer: MediaPlayer? = null
override fun onResume() {
super.onResume()
startBeeping()
}
private fun startBeeping() {
handler = Handler()
handler?.postDelayed(object : Runnable {
override fun run() {
handler?.postDelayed(this, delay.toLong())
playBeepSound1() // SoundPool
// playBeepSound2() // MediaPlayer
}
}, delay.toLong())
}
private fun playBeepSound1() {
val attributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
soundPool = SoundPool.Builder()
.setAudioAttributes(attributes)
.build()
soundPool?.setOnLoadCompleteListener { soundPool, soundId, _ ->
soundPool.play(soundId, 1.0f, 1.0f, 0, 0, 1.0f);
}
soundPool?.load(baseContext, R.raw.beep_sound, 1)
}
private fun playBeepSound2() {
mediaPlayer = MediaPlayer.create(this, R.raw.beep_sound)
mediaPlayer?.start()
}
override fun onPause() {
super.onPause()
stopBeeping()
}
private fun stopBeeping() {
handler?.removeCallbacks(this)
handler = null
soundPool?.release()
soundPool = null
mediaPlayer?.release()
mediaPlayer = null
}
有什么办法可以循环播放短音?
更新一下。
我在不同操作系统版本的设备上进行了测试(Android 6,Android 9,也有模拟器),结果几乎一样。唯一的区别是它停止哔哔声后的时间。
mp3文件大小为5KB。
我不知道kotlin,但这是我如何在Java与MediaPlayer。
MediaPlayer player=MediaPlayer.create(MainActivity.this,R.raw.beep_sound);
for(int i=0;i<45;i++){
//the for loop will make it run 45 times
player.start();
//wait for 600 milliseconds because it's 100 times a minute
Thread.sleep(600);
}
//stop for 30 seconds
Thread.sleep(30000);
//then this time play 10 times only
for(int i=0;i<10;i++){
player.start();
Thread.sleep(600);
}