我正在使用 AudioManager 在拨打电话之前通过听筒播放声音,所以我使用 AudioManager setMode(MODE_IN_CALL)。
除了在 Galaxy S3 中,我没有任何问题,在正确播放音乐后,铃声听起来非常失真且非常嘈杂。我已阅读 setMode 文档:
The audio mode encompasses audio routing AND the behavior of the telephony
layer. Therefore this method should only be used by applications that replace
the platform-wide management of audio settings or the main telephony application.
In particular, the MODE_IN_CALL mode should only be used by the telephony
application when it places a phone call, as it will cause signals from the
radio layer to feed the platform mixer.
所以我怀疑可能有来自无线电层馈送平台混频器的信号。
所以我使用的代码是这样的:
am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
speakerWasOn = am.isSpeakerphoneOn();
speakerPrevMode = am.getMode();
bthA2dpWasOn = am.isBluetoothA2dpOn();
bthScoWasOn = am.isBluetoothScoOn();
if (BluetoothBR.bthOn && BluetoothBR.conectarBluetooth()) {
am.setMode(AudioManager.STREAM_VOICE_CALL);
am.setBluetoothA2dpOn(true);
am.setBluetoothScoOn(true);
} else {
am.setSpeakerphoneOn(false);
am.setMode(AudioManager.MODE_IN_CALL);
}
然后我使用 MediaPlayer 在单独的线程中播放 .mp3 文件:
private OnPreparedListener opl = new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
try {
mp.setVolume(1.0f, 1.0f);
mp.start();
} catch (Throwable e) {
e.printStackTrace();
mp.release();
}
}
};
private OnCompletionListener ocl = new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
stop();
}
};
public void run() {
synchronized (mp) {
FileInputStream fis = null;
try {
fis = new FileInputStream(getMp3FilePath());
mp.setDataSource(fis.getFD());
mp.setOnPreparedListener(opl);
mp.setOnCompletionListener(ocl);
mp.prepare();
fis.close();
} catch (Exception e) {
mp.release();
if (fis != null) {
try {
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
public void stop() {
if (mp != null) {
try {
mp.stop();
mp.release();
mp.setVolume(0.5f, 0.5f);
mp.reset();
} catch (Exception ignored) {
}
}
if (BluetoothBR.bthOn) {
BluetoothBR.desconectarBluetooth();
}
}
当音乐结束时,我会打电话:
am.setSpeakerphoneOn(speakerWasOn);
am.setMode(speakerPrevMode);
am.setBluetoothA2dpOn(bthA2dpWasOn);
am.setBluetoothScoOn(bthScoWasOn);
这仅在三星 Galaxy S3 (afaik) 上发生,并且已经在 S2、华为、索尼爱立信等公司中进行了测试并且工作正常。
有任何想法吗?谢谢
更新:
我发现如果线程在音乐结束时等待 5 秒并且在将 AudioManager 设置为原始状态之后一切正常。
am.setSpeakerphoneOn(speakerWasOn);
am.setMode(speakerPrevMode);
am.setBluetoothA2dpOn(bthA2dpWasOn);
am.setBluetoothScoOn(bthScoWasOn);
long ctime = System.currentTimeMillis();
while (System.currentTimeMillis() - ctime < 5000);