I'm currently using following code to switch the audio stream to ear piece when the device gets close to any object:
@Override
public void onSensorChanged(SensorEvent event) {
if (mAudioManager.isWiredHeadsetOn() || !(mCurrentPlaybackStatus == STATUS_PLAYING
|| mCurrentPlaybackStatus == STATUS_PREPARING)) {
return;
}
boolean isClose = event.values[0] < mSensor.getMaximumRange();
if (!mScreenDisabled && isClose) {
mAudioManager.setMode(AudioManager.STREAM_MUSIC);
mAudioManager.setSpeakerphoneOn(false);
disableScreen();
mScreenDisabled = true;
} else if (mScreenDisabled && !isClose) {
mAudioManager.setSpeakerphoneOn(true);
mAudioManager.setMode(mAudioManagerMode);
enableScreen();
mScreenDisabled = false;
}
}
Unfortunately there is a significant delay when calling .setMode(AudioManager.STREAM_MUSIC);
(> 500ms)
With Android's default MediaPlayer the output stream can be changed without delay:
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL); // ear piece
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // speakerphone
Is there any way to change ExoPlayer's output stream?
Add dependency of ExoPlayer in your application. Add ExoPlayer in your layout file. In your Java/Kotlin file make a function to initialize the player. This function will initialise the ExoPlayer in the player view and it will play the media when the player is ready.
ExoPlayer is an app-level media player built on top of low-level media APIs in Android. It is an open source project used by Google apps, including YouTube and Google TV. ExoPlayer is highly customizable and extensible, making it capable of many advanced use cases.
For changing ExoPlayer's stream type, you need to pass the stream type through the MediaCodecAudioTrackRenderer constructor, into (ExoPlayer's) AudioTrack constructor,
public AudioTrack() {
this(null, AudioManager.STREAM_MUSIC); //default is STREAM_MUSIC
}
public AudioTrack(AudioCapabilities audioCapabilities, int streamType) {
}
So in your application, you'll specify the type when you build the renderer.
Please refer https://github.com/google/ExoPlayer/issues/755 for more info
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With