我正在尝试使用mediaPlayer
通过android中的通话扬声器播放一些音频,但是它总是在外接扬声器中播放。这是我用来更改音频播放位置的代码。
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(tmp_audio_file.getPath());
} catch (IOException e) {
e.printStackTrace();
}
AudioAttributes attributes;
if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
if (event.values[0] >= -SENSOR_SENSITIVITY && event.values[0] <= SENSOR_SENSITIVITY) {
// Speak in the internal speaker
Toast.makeText(getApplicationContext(), "near", Toast.LENGTH_SHORT).show();
// audioManager.setMode(AudioManager.STREAM_VOICE_CALL);
attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
this.mediaPlayer.setAudioAttributes(attributes);
} else {
// Speak in the external speaker
Toast.makeText(getApplicationContext(), "far", Toast.LENGTH_SHORT).show();
// audioManager.setMode(AudioManager.MODE_NORMAL);
attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
this.mediaPlayer.setAudioAttributes(attributes);
}
}
if (this.play) {
try {
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(getApplicationContext(), "playing", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
应用程序的目标是SDK 28,因此mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL)
都不起作用。
设置扬声器在播放音频时使用的正确方法是什么?