AudioManager MODE_IN_CALL干扰

时间:2013-03-02 22:36:54

标签: android media-player android-audiomanager

我正在使用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,华为,索尼爱立信等测试过,并且运行正常。

任何想法? 感谢

更新

我发现如果音乐在音乐结束时以及将AudioManager设置为原始状态后等待5秒钟,一切正常。

am.setSpeakerphoneOn(speakerWasOn);
am.setMode(speakerPrevMode);
am.setBluetoothA2dpOn(bthA2dpWasOn);
am.setBluetoothScoOn(bthScoWasOn);

long ctime = System.currentTimeMillis();
while (System.currentTimeMillis() - ctime < 5000);

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。当我注释掉这一行时

am.setMode(AudioManager.MODE_IN_CALL);

一切都对我很好。