在我的Android应用程序中,我想在手机内部扬声器上播放声音,即使用户通过蓝牙设备或其他外部扬声器连接到设备上。这能办到吗?
发布于 2022-09-07 17:15:07
我想出了在电话扬声器上播放音频的方法,即使我有一个连接的蓝牙音频设备:
fun createPhoneSpeakerPreferredPlayer(context: Context, resource: Int): MediaPlayer{
val mediaPlayer = MediaPlayer.create(context, resource)
val audioDeviceType = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) AudioDeviceInfo.TYPE_BUILTIN_SPEAKER_SAFE else AudioDeviceInfo.TYPE_BUILTIN_SPEAKER
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
val devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
//create mapped devices variable to allow better logging. The devices collection is not being serialized well (or at all)
val mappedDevices = (devices.map {
@Suppress("unused")
object {
val id = it.id
val type = it.type
val productName = it.productName
}})
val jsonRepresentation = Gson().toJson(mappedDevices)
Log.d(Tag, "devices: $jsonRepresentation")
val playbackDevice = devices.firstOrNull { it.type == audioDeviceType }
Log.d(Tag, "selectedDevice: {id=${playbackDevice?.id}}, type=\"${playbackDevice?.type}\", productName=\"${playbackDevice?.productName}\"")
mediaPlayer.preferredDevice = playbackDevice
return mediaPlayer
}要使用该方法并播放音频:
val mediaPlayer = createPhoneSpeakerPreferredPlayer(this.context, R.raw.myAudioId)
mediaPlayer.looping = true
mediaPlayer.start()如果我连接了蓝牙扬声器,这似乎是可行的,但一旦我开始在后台播放音频,比如观看Netflix,或收听播客,这些音频就不再在电话扬声器上播放。
下面是我用两个按钮制作的一个示例应用程序。一个通过电话扬声器播放音乐,另一个通过任何连接的扬声器播放:
我看到,当我第一次创建一个媒体播放器并以这种方式播放声音时,声音确实会在电话扬声器上播放。第二个音频在蓝牙扬声器上播放。当我没有播放任何视频或音乐,但仍然连接到蓝牙设备时,我的声音都会在电话扬声器上播放。以下是显示我正确设置首选设备的日志:
2022-09-07 11:21:33.969 6101-6101/com.myApp D/MediaPlayerExtensions: devices: [{"id":2,"productName":"Pixel 3","type":1},{"id":3,"productName":"Pixel 3","type":2},{"id":11,"productName":"Pixel 3","type":18},{"id":369,"productName":"Jabra Elite 85h","type":8},{"id":363,"productName":"Jabra Elite 85h","type":7}]
2022-09-07 11:21:33.969 6101-6101/com.myApp D/MediaPlayerExtensions: selectedDevice: {id=3}, type="2", productName="Pixel 3"
2022-09-07 11:22:14.290 6101-6101/com.myApp D/MediaPlayerExtensions: devices: [{"id":2,"productName":"Pixel 3","type":1},{"id":3,"productName":"Pixel 3","type":2},{"id":11,"productName":"Pixel 3","type":18},{"id":369,"productName":"Jabra Elite 85h","type":8},{"id":363,"productName":"Jabra Elite 85h","type":7}]
2022-09-07 11:22:14.290 6101-6101/com.myApp D/MediaPlayerExtensions: selectedDevice: {id=3}, type="2", productName="Pixel 3"https://stackoverflow.com/questions/73639204
复制相似问题