timoschloesser
timoschloesser

Reputation: 2802

Exoplayer: How to play audio through ear piece?

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?

Upvotes: 8

Views: 2043

Answers (3)

Yousef Kazemi
Yousef Kazemi

Reputation: 164

In exoPlayer, I solved it by these: Use this function to change the speaker to ear piece

audioPlayer.setAudioStreamType(C.STREAM_TYPE_VOICE_CALL);

and vise versa(using the phone speaker)

audioPlayer.setAudioStreamType(C.STREAM_TYPE_MUSIC);

But in newer versions of exoPlayer, this function has been deleted. Instead of that use this:

fun setAttributes(@C.StreamType streamType: Int) {
    @AudioUsage val usage = Util.getAudioUsageForStreamType(streamType)
    @AudioContentType val contentType =
        Util.getAudioContentTypeForStreamType(streamType)
    val audioAttributes =
        AudioAttributes.Builder().setUsage(usage).setContentType(contentType).build()
    audioPlayer.setAudioAttributes(audioAttributes, false)
}

And finally call the function:

setAttributes(C.STREAM_TYPE_VOICE_CALL)

or

setAttributes(C.STREAM_TYPE_MUSIC)

Upvotes: 0

abhishesh
abhishesh

Reputation: 3316

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

Upvotes: 2

Ajay Venugopal
Ajay Venugopal

Reputation: 1700

Play through the ear piece

mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);

Upvotes: 0

Related Questions