这个声音很简单,我无法弄清楚为什么我找不到答案lol
我有一个有效的声音池类(感谢教程和我做过的一些调整),它工作正常。
现在的问题是我希望能够随机改变我的背景音乐。 (并不总是在循环中有相同的音乐,但有2或3,当一个完成时,我会播放其他2个中的一个)。
问题是我找不到通知音乐播放完毕的方法。
有什么想法吗?
杰森
答案 0 :(得分:15)
这就是我的所作所为:
在启动上,我使用MediaPlayer获取每次声音点击的长度:
private long getSoundDuration(int rawId){
MediaPlayer player = MediaPlayer.create(context, rawId);
int duration = player.getDuration();
return duration;
}
并将声音加上持续时间存储在一起(在DTO类型的对象中)。
答案 1 :(得分:12)
据我所知,无法用SoundPool完成。
我知道唯一能提供完成通知的音频'播放器'是 MediaPlayer - 它比SoundPool更复杂,但允许设置OnCompletionListener在播放完成时得到通知。
答案 2 :(得分:5)
我有超过100个短声音片段,SoundPool是我的最佳选择。我想在另一个剪辑完成播放后播放一个剪辑。一旦发现没有onCompletionListener()等价,我选择实现runnable。这对我有用,因为第一个声音长度在1到2秒之间,因此我将runnable的持续时间设置为2000.希望它们能够在这个类上工作,因为它有很大的潜力!
答案 3 :(得分:3)
与SoundPool相比,MediaPlayer又重又慢,但SoundPool没有setOnCompletionListener。为了解决这个问题,我使用setOnCompletionListener从SoundPool实现了custom class。
用法:类似于MediaPlayer
SoundPoolPlayer mPlayer = SoundPoolPlayer.create(context, resId);
mPlayer.setOnCompletionListener(
new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) { //mp will be null here
Log.d("debug", "completed");
}
};
);
mPlayer.play();
mPlayer.pause();
mPlayer.stop();
mPlayer.resume();
mPlayer.isPlaying();
欢迎任何拉动请求。我只在这里实现了我需要的东西。
答案 4 :(得分:1)
我遇到了类似的问题,并创建了一个SoundPool队列,该队列使要播放的声音排队,并在每种声音完成播放时通知。它在Kotlin中,但是应该很容易翻译成Java。
class SoundPoolQueue(private val context: Context, maxStreams: Int) {
companion object {
private const val LOG_TAG = "SoundPoolQueue"
private const val SOUND_POOL_HANDLER_THREAD_NAME = "SoundPoolQueueThread"
private const val ACTION_PLAY_SOUND = 1
@JvmStatic
fun getSoundDuration(context: Context, soundResId: Int) : Long {
val assetsFileDescriptor = context.resources.openRawResourceFd(soundResId)
val mediaMetadataRetriever = MediaMetadataRetriever()
mediaMetadataRetriever.setDataSource(
assetsFileDescriptor.fileDescriptor,
assetsFileDescriptor.startOffset,
assetsFileDescriptor.length)
val durationString = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
val duration = durationString.toLong()
logDebug("SoundPoolQueue::getSoundDuration(): Sound duration millis: $durationString")
assetsFileDescriptor.close()
return duration
}
@JvmStatic
private fun logDebug(message: String) {
if(!BuildConfig.DEBUG) {
return
}
Log.d(LOG_TAG, message)
}
}
private var soundPool = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val attrs = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
SoundPool.Builder()
.setMaxStreams(maxStreams)
.setAudioAttributes(attrs)
.build()
}
else {
@Suppress("DEPRECATION")
SoundPool(maxStreams, AudioManager.STREAM_NOTIFICATION, 0)
}
var soundPoolQueueListener : SoundPoolQueueListener? = null
private val soundPoolHandlerThread = SoundPoolQueueThread().apply { start() }
private val soundPoolSoundsSparseArray = SparseArray<SoundPoolSound>()
private val soundPoolSoundsQueue = LinkedList<SoundPoolSound>()
fun addSound(soundResId: Int, leftVolume: Float, rightVolume: Float, priority: Int, loop: Boolean, rate: Float) {
val durationMillis = getSoundDuration(context = context, soundResId = soundResId)
val soundId = soundPool.load(context, soundResId, priority)
soundPoolSoundsSparseArray.put(soundResId,
SoundPoolSound(durationMillis, soundResId, soundId, leftVolume, rightVolume, priority, loop, rate))
}
fun playSound(soundResId: Int) {
logDebug("SoundPoolQueue::playSound()")
soundPoolSoundsQueue.add(soundPoolSoundsSparseArray[soundResId])
soundPoolHandlerThread.handler?.sendEmptyMessage(ACTION_PLAY_SOUND)
}
inner class SoundPoolQueueThread : HandlerThread(SOUND_POOL_HANDLER_THREAD_NAME) {
var handler: Handler? = null
override fun onLooperPrepared() {
super.onLooperPrepared()
handler = object : Handler(looper) {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
if(msg.what == ACTION_PLAY_SOUND && handler!!.hasMessages(ACTION_PLAY_SOUND)) {
return
}
if(soundPoolSoundsQueue.isEmpty()) {
logDebug("SoundPoolHandlerThread: queue is empty.")
handler!!.removeMessages(ACTION_PLAY_SOUND)
return
}
logDebug("SoundPoolHandlerThread: Playing sound!")
logDebug("SoundPoolHandlerThread: ${soundPoolSoundsQueue.size} sounds left for playing.")
val soundPoolSound = soundPoolSoundsQueue.pop()
soundPool.play(soundPoolSound.soundPoolSoundId,
soundPoolSound.leftVolume,
soundPoolSound.rightVolume,
soundPoolSound.priority,
if(soundPoolSound.loop) { 1 } else { 0 },
soundPoolSound.rate)
try {
Thread.sleep(soundPoolSound.duration)
}
catch (ex: InterruptedException) { }
//soundPoolQueueListener?.onSoundPlaybackCompleted(soundPoolSound.soundResId)
sendEmptyMessage(0)
}
}
}
}
interface SoundPoolQueueListener {
fun onSoundPlaybackCompleted(soundResId: Int)
}
}
随附的数据类
data class SoundPoolSound(val duration: Long,
val soundResId: Int,
val soundPoolSoundId: Int,
val leftVolume: Float,
val rightVolume: Float,
val priority: Int,
val loop: Boolean,
val rate: Float)
当声音在
中播放完毕时,您会收到通知onSoundPlaybackCompleted(soundResId: Int)
具有已完成播放声音的资源ID。
用法示例:
private class SoundPoolRunnable implements Runnable {
@Override
public void run() {
LogUtils.debug(SerializableNames.LOG_TAG, "SoundPoolRunnable:run(): Initializing sounds!");
m_soundPoolPlayer = new SoundPoolQueue(GSMSignalMonitorApp.this, 1);
m_soundPoolPlayer.setSoundPoolQueueListener(new SoundPoolQueue.SoundPoolQueueListener() {
@Override
public void onSoundPlaybackCompleted(int soundResId)
{
LogUtils.debug(SerializableNames.LOG_TAG, "onSoundPlaybackCompleted() " + soundResId);
}
});
m_soundPoolPlayer.addSound(R.raw.gsm_signal_lost, 0.2f, 0.2f, 1, false, 1.0f);
m_soundPoolPlayer.addSound(R.raw.gsm_signal_restored, 0.2f, 0.2f, 1, false, 1.0f);
m_soundPoolPlayer.addSound(R.raw.gsm_signal_low, 0.2f, 0.2f, 1, false, 1.0f);
m_soundPoolPlayer.addSound(R.raw.gsm_signal_lost_ru, 0.2f, 0.2f, 1, false, 1.0f);
m_soundPoolPlayer.addSound(R.raw.gsm_signal_restored_ru, 0.2f, 0.2f, 1, false, 1.0f);
m_soundPoolPlayer.addSound(R.raw.gsm_signal_low_ru, 0.2f, 0.2f, 1, false, 1.0f);
}
}
希望它会有所帮助:)