我正在寻找一种从Android设备的扬声器播放音频的方法,即使插入耳机也是如此。
实际上,典型的行为是,当插入耳机时,扬声器不输出音频。但是,某些应用程序(例如默认的时钟应用程序(com.google.android.deskclock))即使在插入耳机时也能够将音频路由到扬声器。
如何以编程方式获取此行为?
我正在寻找适用于(至少)Nexus 5设备的解决方案,运行KitKat(Android 4.4)
感谢。
答案 0 :(得分:2)
看看这个应用程序的源代码可能会有所帮助。我找到了一个可以完成工作的AsyncRingtonePlayer(https://android.googlesource.com/platform/packages/apps/DeskClock/+/master/src/com/android/deskclock/AsyncRingtonePlayer.java)类。
我想,诀窍是使用不同的Audiostream。让我们来看看startAlarm方法:
private void startAlarm(MediaPlayer player) throws IOException {
// do not play alarms if stream volume is 0 (typically because ringer mode is silent).
if (mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
if (Utils.isLOrLater()) {
player.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());
}
player.setAudioStreamType(AudioManager.STREAM_ALARM);
player.setLooping(true);
player.prepare();
mAudioManager.requestAudioFocus(null, AudioManager.STREAM_ALARM,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
player.start();
}
}
播放器对象的音频流类型将设置为 AudioManager.STREAM_ALARM 。我想这可能是解决方案。我没有测试它,但这是我在源代码中找到的第一件事。
请注意AndroidManifest中列出的一些所需权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<!-- WRITE_SETTINGS is required to record the upcoming alarm prior to L -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!-- READ_PHONE_STATE is required to determine when a phone call exists prior to M -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- READ_EXTERNAL_STORAGE is required to play custom ringtones from the SD card prior to M -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
(https://android.googlesource.com/platform/packages/apps/DeskClock/+/master/AndroidManifest.xml)
答案 1 :(得分:0)
删除Android 4.4不需要的代码
//context = a valid context
AudioManager am = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
MediaPlayer mp = new MediaPlayer();
Uri loc = Uri.parse("android.resource://com.example.test/" + R.raw.music);
try {
mp.setDataSource(context, loc);
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setLooping(true);
mp.prepare();
} catch (IllegalArgumentException | SecurityException| IllegalStateException | IOException e) {
e.printStackTrace();
}
am.requestAudioFocus(null, AudioManager.STREAM_ALARM,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
mp.start();