【问题标题】:Play Sound on Notification Stream在通知流上播放声音
【发布时间】:2020-03-07 14:34:03
【问题描述】:

我检查了什么应用程序,当您在聊天中时,发送/接收消息的声音仅在 Android 上的 NOTIFICATION 流上播放。

我们在android中有四个流通道:

  • 铃声
  • 媒体
  • 通知
  • 系统

我想在 Notification 流中播放声音。

似乎不起作用的示例代码:

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()
    }

【问题讨论】:

    标签: java android android-mediaplayer android-notifications


    【解决方案1】:

    添加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()
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-11
      • 2012-04-23
      • 2012-01-14
      • 1970-01-01
      • 2015-02-04
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多