[英]Play Sound on Notification Stream
I checked whats app and the send/receive message sounds play only on NOTIFICATION stream on android when you're inside a chat.我检查了 whats 应用程序,当您在聊天中时,发送/接收消息声音仅在 android 上的通知流上播放。
We have four stream channels in android:我们在 android 中有四个流通道:
I want to play sound on Notification stream.我想在通知流上播放声音。
Sample Code that doesn't seem to work:似乎不起作用的示例代码:
try {
with(mediaPlayer) {
reset()
setDataSource(
requireContext(),
Uri.parse("android.resource://${requireContext().packageName}/" + R.raw.sound_all_outgoingmessage)
)
setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
setAudioAttributes(
AudioAttributes
.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build())
prepare()
setOnCompletionListener { play = true }
if (!isPlaying && play) {
play = false
start()
}
}
} catch (e: Exception) {
play = true
e.printStackTrace()
}
Adding setUsage()
method fixed my problem.添加
setUsage()
方法解决了我的问题。
fun playSound(context: Context, source: Uri) {
if (!mPlay) return
try {
with(mMediaPlayer) {
reset()
setDataSource(context, source)
if (android.os.Build.VERSION.SDK_INT >= 21) {
val audioAttribute = android.media.AudioAttributes.Builder()
.setUsage(android.media.AudioAttributes.USAGE_NOTIFICATION)
.setContentType(android.media.AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
setAudioAttributes(audioAttribute)
}
setVolume(0.2f, 0.2f)
prepare()
setOnCompletionListener { mPlay = true }
if (!isPlaying && mPlay) {
mPlay = false
start()
}
}
} catch (e: Exception) {
mPlay = true
e.printStackTrace()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.