在我的应用程序中,有一个使用设备音频插孔的读卡器。现在,我的问题是,当读卡器在设备的耳机插孔中完好无损时,我想从内置扬声器中发出声音。
以下是我尝试过的代码:
1) 使用反射方法
Class audioSystemClass;
try {
audioSystemClass = Class
.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod(
"setForceUse", int.class, int.class);
// First 1 == FOR_MEDIA, second 1 == FORCE_SPEAKER. To go
// back to the default
// behavior, use FORCE_NONE (0).
setForceUse.invoke(null, 1, 1);
final float maxVolume = mAudioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
soundPool.play(soundID, maxVolume, maxVolume, 1, 0, 1f);
} catch (ClassNotFoundException e) {
Log.e("Test", e.toString());
e.printStackTrace();
} catch (NoSuchMethodException e) {
Log.e("Test", e.toString());
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.e("Test", e.toString());
e.printStackTrace();
} catch (IllegalArgumentException e) {
Log.e("Test", e.toString());
e.printStackTrace();
} catch (InvocationTargetException e) {
Log.e("Test", e.toString());
e.printStackTrace();
}
2)使用setMode方法
mAudioManager.setMode(AudioManager.MODE_IN_CALL);
mAudioManager.setSpeakerphoneOn(true);
float maxVolume = mAudioManager
.getStreamMaxVolume(AudioManager.STREAM_RING);
soundPool.play(soundID, maxVolume, maxVolume, 1, 0, 1f);
但这两种代码仅在具有默认FM应用程序的设备中运行。但我想在所有设备中都具有此功能。
请分享你的经验!!
或者,如果您将 SoundPool 初始化为STREAM_VOICE_CALL,则为:
SoundPool spool=新的声音池(1,AudioManager.STREAM_VOICE_CALL,0)
那么您的音频也应该以您上面提到的任何方式路由到扬声器。我试过了,即使没有默认FM,它也可以在手机上工作。
您的第二种方法setMode适用于具有默认Fm播放器的手机。
但是,对于没有默认FM的设备,我尝试了以下代码:
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
mAudioManager.setSpeakerphoneOn(true);
这段代码在没有默认Fm播放器的手机上运行良好。我用了一个装有氧气操作系统的一加设备,工作正常。希望这有所帮助。
在这里,我已经启动了一个SoundPool并加载了一个beep。
SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_VOICE_CALL, 0);
soundPool
.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool,
int sampleId, int status) {
loaded = true;
}
});
soundID = soundPool.load(ApplicationChexology.getContext(), R.raw.beep_single, 1);
现在,在加载声音后,我将AudioManager设置为MODE_IN_COMMUNICATION并播放声音。播放声音后,将音频管理器的模式设置为mode_NORMAL。
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(true);
float maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
if (loaded)
soundPool.play(soundID, maxVolume, maxVolume, 1, 0, 1f);
Timer timer = new Timer();
TimerTask delayedThreadStartTask = new TimerTask() {
@Override
public void run() {
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setSpeakerphoneOn(false);
}};
timer.schedule(delayedThreadStartTask, 500);