【问题标题】:Beep sound played in a loop stops after some time for both SoundPool and MediaPlayerSoundPool 和 MediaPlayer 在一段时间后循环播放的哔声停止
【发布时间】:2020-04-19 14:19:15
【问题描述】:

我尝试连续播放一个简短的 .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。

【问题讨论】:

  • 在这两种情况下,您每次玩游戏时都会创建新实例,而永远不会释放旧实例。相反,创建一个实例,然后一遍又一遍地重播它。
  • @MikeM。你是对的!创建一个实例后,MediaPool start() 工作正常,但 SoundPool play() 不播放任何声音...

标签: android kotlin android-mediaplayer mp3 soundpool


【解决方案1】:

我不知道 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);
}

【讨论】:

  • 感谢您的回答,但 1) 30 秒暂停是一个错误,不是必需的 2) 我更喜欢处理程序而不是调用睡眠函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多