使用 MediaPlayer 播放声音时出现无效属性错误

Getting invalid attributes error when playing sound with MediaPlayer

当我调用 mediaPlayer.start() 时,我的应用程序突然没有播放声音。

我在日志中收到以下错误:

2020-05-29 20:43:57.165 4719-1953/? E/AudioSystem: invalid attributes { Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: -1 Flags: 0x800 Tags:  } when converting to stream

我在应用程序启动时执行此操作:

mMediaPlayer = MediaPlayer.create(context, R.raw.restaurant_order_received)

感谢帮助

您需要提供一个resourceID。试试这个:

var resID = context?.resources?.getIdentifier("YOUR_FILE_NAME", "raw", context.packageName)

resID?.let {
    // No fike found when it == 0
    if (it == 0) {
        val errorString = "Error occured."
        Snackbar.make(view, errorString, 2000).show()
        return
    }
    mediaPlayer = MediaPlayer.create(context, it)
    mediaPlayer?.start()
    return
}

我没有属性配置...

所以就这样做:

mMediaPlayer = MediaPlayer()
mMediaPlayer.setAudioAttributes(AudioAttributes.Builder()
    .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
    .setLegacyStreamType(AudioManager.STREAM_MUSIC)
    .setUsage(AudioAttributes.USAGE_ALARM)
    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
    .build())
mMediaPlayer.setDataSource(context, Uri.parse("android.resource://com.mypackage.name/raw/restaurant_order_received"))
mMediaPlayer.isLooping = true
mMediaPlayer.prepare()