com.google.android.exoplayer2.audio.AudioAttributes Java Examples

The following examples show how to use com.google.android.exoplayer2.audio.AudioAttributes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AudioFocusManager.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Sets audio attributes that should be used to manage audio focus.
 *
 * @param audioAttributes The audio attributes or {@code null} if audio focus should not be
 *     managed automatically.
 * @param playWhenReady The current state of {@link ExoPlayer#getPlayWhenReady()}.
 * @param playerState The current player state; {@link ExoPlayer#getPlaybackState()}.
 * @return A {@link PlayerCommand} to execute on the player.
 */
@PlayerCommand
public int setAudioAttributes(
    @Nullable AudioAttributes audioAttributes, boolean playWhenReady, int playerState) {
  if (!Util.areEqual(this.audioAttributes, audioAttributes)) {
    this.audioAttributes = audioAttributes;
    focusGain = convertAudioAttributesToFocusGain(audioAttributes);

    Assertions.checkArgument(
        focusGain == C.AUDIOFOCUS_GAIN || focusGain == C.AUDIOFOCUS_NONE,
        "Automatic handling of audio focus is only available for USAGE_MEDIA and USAGE_GAME.");
    if (playWhenReady
        && (playerState == Player.STATE_BUFFERING || playerState == Player.STATE_READY)) {
      return requestAudioFocus();
    }
  }

  return playerState == Player.STATE_IDLE
      ? handleIdle(playWhenReady)
      : handlePrepare(playWhenReady);
}
 
Example #2
Source File: SimpleExoPlayer.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setAudioAttributes(AudioAttributes audioAttributes) {
  if (Util.areEqual(this.audioAttributes, audioAttributes)) {
    return;
  }
  this.audioAttributes = audioAttributes;
  for (Renderer renderer : renderers) {
    if (renderer.getTrackType() == C.TRACK_TYPE_AUDIO) {
      player
          .createMessage(renderer)
          .setType(C.MSG_SET_AUDIO_ATTRIBUTES)
          .setPayload(audioAttributes)
          .send();
    }
  }
  for (AudioListener audioListener : audioListeners) {
    audioListener.onAudioAttributesChanged(audioAttributes);
  }
}
 
Example #3
Source File: SimpleExoPlayer.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setAudioAttributes(AudioAttributes audioAttributes) {
  if (Util.areEqual(this.audioAttributes, audioAttributes)) {
    return;
  }
  this.audioAttributes = audioAttributes;
  for (Renderer renderer : renderers) {
    if (renderer.getTrackType() == C.TRACK_TYPE_AUDIO) {
      player
          .createMessage(renderer)
          .setType(C.MSG_SET_AUDIO_ATTRIBUTES)
          .setPayload(audioAttributes)
          .send();
    }
  }
  for (AudioListener audioListener : audioListeners) {
    audioListener.onAudioAttributesChanged(audioAttributes);
  }
}
 
Example #4
Source File: SimpleExoPlayer.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setAudioAttributes(AudioAttributes audioAttributes, boolean handleAudioFocus) {
  verifyApplicationThread();
  if (!Util.areEqual(this.audioAttributes, audioAttributes)) {
    this.audioAttributes = audioAttributes;
    for (Renderer renderer : renderers) {
      if (renderer.getTrackType() == C.TRACK_TYPE_AUDIO) {
        player
            .createMessage(renderer)
            .setType(C.MSG_SET_AUDIO_ATTRIBUTES)
            .setPayload(audioAttributes)
            .send();
      }
    }
    for (AudioListener audioListener : audioListeners) {
      audioListener.onAudioAttributesChanged(audioAttributes);
    }
  }

  @AudioFocusManager.PlayerCommand
  int playerCommand =
      audioFocusManager.setAudioAttributes(
          handleAudioFocus ? audioAttributes : null, getPlayWhenReady(), getPlaybackState());
  updatePlayWhenReady(getPlayWhenReady(), playerCommand);
}
 
Example #5
Source File: SimpleExoPlayer.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setAudioAttributes(AudioAttributes audioAttributes, boolean handleAudioFocus) {
  verifyApplicationThread();
  if (!Util.areEqual(this.audioAttributes, audioAttributes)) {
    this.audioAttributes = audioAttributes;
    for (Renderer renderer : renderers) {
      if (renderer.getTrackType() == C.TRACK_TYPE_AUDIO) {
        player
            .createMessage(renderer)
            .setType(C.MSG_SET_AUDIO_ATTRIBUTES)
            .setPayload(audioAttributes)
            .send();
      }
    }
    for (AudioListener audioListener : audioListeners) {
      audioListener.onAudioAttributesChanged(audioAttributes);
    }
  }

  @AudioFocusManager.PlayerCommand
  int playerCommand =
      audioFocusManager.setAudioAttributes(
          handleAudioFocus ? audioAttributes : null, getPlayWhenReady(), getPlaybackState());
  updatePlayWhenReady(getPlayWhenReady(), playerCommand);
}
 
Example #6
Source File: AnalyticsCollector.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public void onAudioAttributesChanged(AudioAttributes audioAttributes) {
  EventTime eventTime = generateReadingMediaPeriodEventTime();
  for (AnalyticsListener listener : listeners) {
    listener.onAudioAttributesChanged(eventTime, audioAttributes);
  }
}
 
Example #7
Source File: AnalyticsCollector.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onAudioAttributesChanged(AudioAttributes audioAttributes) {
  EventTime eventTime = generateReadingMediaPeriodEventTime();
  for (AnalyticsListener listener : listeners) {
    listener.onAudioAttributesChanged(eventTime, audioAttributes);
  }
}
 
Example #8
Source File: EventLogger.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public void onAudioAttributesChanged(EventTime eventTime, AudioAttributes audioAttributes) {
  logd(
      eventTime,
      "audioAttributes",
      audioAttributes.contentType
          + ","
          + audioAttributes.flags
          + ","
          + audioAttributes.usage
          + ","
          + audioAttributes.allowedCapturePolicy);
}
 
Example #9
Source File: ExoPlayerFacade.java    From no-player with Apache License 2.0 5 votes vote down vote up
private void setMovieAudioAttributes(SimpleExoPlayer exoPlayer) {
    if (androidDeviceVersion.isLollipopTwentyOneOrAbove()) {
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setContentType(C.CONTENT_TYPE_MOVIE)
                .build();
        exoPlayer.setAudioAttributes(audioAttributes);
    }
}
 
Example #10
Source File: ExoPlayerFacadeTest.java    From no-player with Apache License 2.0 5 votes vote down vote up
@Test
public void givenLollipopDevice_whenLoadingVideo_thenSetsMovieAudioAttributesOnExoPlayer() {
    given(androidDeviceVersion.isLollipopTwentyOneOrAbove()).willReturn(true);

    facade.loadVideo(surfaceViewHolder, drmSessionCreator, uri, OPTIONS, exoPlayerForwarder, mediaCodecSelector);

    AudioAttributes expectedMovieAudioAttributes = new AudioAttributes.Builder()
            .setContentType(C.CONTENT_TYPE_MOVIE)
            .build();
    verify(exoPlayer).setAudioAttributes(expectedMovieAudioAttributes);
}
 
Example #11
Source File: SimpleExoPlayer.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public void setAudioAttributes(AudioAttributes audioAttributes, boolean handleAudioFocus) {
  verifyApplicationThread();
  if (playerReleased) {
    return;
  }
  if (!Util.areEqual(this.audioAttributes, audioAttributes)) {
    this.audioAttributes = audioAttributes;
    for (Renderer renderer : renderers) {
      if (renderer.getTrackType() == C.TRACK_TYPE_AUDIO) {
        player
            .createMessage(renderer)
            .setType(C.MSG_SET_AUDIO_ATTRIBUTES)
            .setPayload(audioAttributes)
            .send();
      }
    }
    for (AudioListener audioListener : audioListeners) {
      audioListener.onAudioAttributesChanged(audioAttributes);
    }
  }

  @AudioFocusManager.PlayerCommand
  int playerCommand =
      audioFocusManager.setAudioAttributes(
          handleAudioFocus ? audioAttributes : null, getPlayWhenReady(), getPlaybackState());
  updatePlayWhenReady(getPlayWhenReady(), playerCommand);
}
 
Example #12
Source File: AnalyticsCollector.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onAudioAttributesChanged(AudioAttributes audioAttributes) {
  EventTime eventTime = generateReadingMediaPeriodEventTime();
  for (AnalyticsListener listener : listeners) {
    listener.onAudioAttributesChanged(eventTime, audioAttributes);
  }
}
 
Example #13
Source File: ExoPlayerFacadeTest.java    From no-player with Apache License 2.0 5 votes vote down vote up
@Test
public void givenNonLollipopDevice_whenLoadingVideo_thenDoesNotSetAudioAttributesOnExoPlayer() {
    given(androidDeviceVersion.isLollipopTwentyOneOrAbove()).willReturn(false);

    facade.loadVideo(surfaceViewHolder, drmSessionCreator, uri, OPTIONS, exoPlayerForwarder, mediaCodecSelector);

    verify(exoPlayer, never()).setAudioAttributes(any(AudioAttributes.class));
}
 
Example #14
Source File: AnalyticsCollector.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onAudioAttributesChanged(AudioAttributes audioAttributes) {
  EventTime eventTime = generateReadingMediaPeriodEventTime();
  for (AnalyticsListener listener : listeners) {
    listener.onAudioAttributesChanged(eventTime, audioAttributes);
  }
}
 
Example #15
Source File: AnalyticsCollector.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onAudioAttributesChanged(AudioAttributes audioAttributes) {
  EventTime eventTime = generateReadingMediaPeriodEventTime();
  for (AnalyticsListener listener : listeners) {
    listener.onAudioAttributesChanged(eventTime, audioAttributes);
  }
}
 
Example #16
Source File: VideoPlayer.java    From media_player with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static void setAudioAttributes(SimpleExoPlayer exoPlayer) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        exoPlayer.setAudioAttributes(new AudioAttributes.Builder().setContentType(C.CONTENT_TYPE_MOVIE).build());
    } else {
        exoPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }
}
 
Example #17
Source File: ExoMediaPlayer.java    From ExoMedia with Apache License 2.0 5 votes vote down vote up
public void setAudioStreamType(int streamType) {
    @C.AudioUsage
    int usage = Util.getAudioUsageForStreamType(streamType);
    @C.AudioContentType
    int contentType = Util.getAudioContentTypeForStreamType(streamType);

    AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setUsage(usage)
            .setContentType(contentType)
            .build();

    sendMessage(C.TRACK_TYPE_AUDIO, C.MSG_SET_AUDIO_ATTRIBUTES, audioAttributes);
}
 
Example #18
Source File: AudioSlidePlayer.java    From deltachat-android with GNU General Public License v3.0 4 votes vote down vote up
private void play(final double progress, boolean earpiece) throws IOException {
  if (this.mediaPlayer != null) {
    return;
  }

  if (slide.getUri() == null) {
    throw new IOException("Slide has no URI!");
  }

  LoadControl loadControl = new DefaultLoadControl.Builder().setBufferDurationsMs(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE).createDefaultLoadControl();
  this.mediaPlayer           = ExoPlayerFactory.newSimpleInstance(context, new DefaultRenderersFactory(context), new DefaultTrackSelector(), loadControl);
  this.startTime             = System.currentTimeMillis();

  mediaPlayer.prepare(createMediaSource(slide.getUri()));
  mediaPlayer.setPlayWhenReady(true);
  mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
          .setContentType(earpiece ? C.CONTENT_TYPE_SPEECH : C.CONTENT_TYPE_MUSIC)
          .setUsage(earpiece ? C.USAGE_VOICE_COMMUNICATION : C.USAGE_MEDIA)
          .build());
  mediaPlayer.addListener(new Player.EventListener() {

    boolean started = false;

    @Override
    public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
      Log.d(TAG, "onPlayerStateChanged(" + playWhenReady + ", " + playbackState + ")");
      switch (playbackState) {
        case Player.STATE_READY:

          Log.i(TAG, "onPrepared() " + mediaPlayer.getBufferedPercentage() + "% buffered");
          synchronized (AudioSlidePlayer.this) {
            if (mediaPlayer == null) return;
            Log.d(TAG, "DURATION: " + mediaPlayer.getDuration());

            if (started) {
              Log.d(TAG, "Already started. Ignoring.");
              return;
            }

            started = true;

            if (progress > 0) {
              mediaPlayer.seekTo((long) (mediaPlayer.getDuration() * progress));
            }

            setPlaying(AudioSlidePlayer.this);
          }

          notifyOnStart();
          progressEventHandler.sendEmptyMessage(0);
          break;

        case Player.STATE_ENDED:
          Log.i(TAG, "onComplete");
          synchronized (AudioSlidePlayer.this) {
            getListener().onReceivedDuration(Long.valueOf(mediaPlayer.getDuration()).intValue());
            mediaPlayer = null;
          }

          notifyOnStop();
          progressEventHandler.removeMessages(0);
      }
    }

    @Override
    public void onPlayerError(ExoPlaybackException error) {
      Log.w(TAG, "MediaPlayer Error: " + error);

      Toast.makeText(context, R.string.error, Toast.LENGTH_SHORT).show();

      synchronized (AudioSlidePlayer.this) {
        mediaPlayer = null;
      }

      notifyOnStop();
      progressEventHandler.removeMessages(0);
    }
  });
}
 
Example #19
Source File: SimpleExoPlayer.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
@Override
public AudioAttributes getAudioAttributes() {
  return audioAttributes;
}
 
Example #20
Source File: Player.java    From zapp with MIT License 4 votes vote down vote up
public Player(Context context) {
	settings = new SettingsRepository(context);
	networkConnectionHelper = new NetworkConnectionHelper(context);

	String userAgent = Util.getUserAgent(context, context.getString(R.string.app_name));
	TransferListener transferListener = new OnlyWifiTransferListener();
	dataSourceFactory = new DefaultDataSourceFactory(context, userAgent, transferListener);
	TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory();
	DefaultTrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);

	player = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
	playerHandler = new Handler(player.getApplicationLooper());
	trackSelectorWrapper = new TrackSelectorWrapper(trackSelector);

	// media session setup
	mediaSession = new MediaSessionCompat(context, context.getPackageName());
	MediaSessionConnector mediaSessionConnector = new MediaSessionConnector(mediaSession);
	mediaSessionConnector.setPlayer(player, null);
	mediaSession.setActive(true);

	// audio focus setup
	AudioAttributes audioAttributes = new AudioAttributes.Builder()
		.setUsage(C.USAGE_MEDIA)
		.setContentType(C.CONTENT_TYPE_MOVIE)
		.build();
	player.setAudioAttributes(audioAttributes, true);

	playerEventHandler = new PlayerEventHandler();

	// enable subtitles
	enableSubtitles(settings.getEnableSubtitles());

	// wakelocks
	playerWakeLocks = new PlayerWakeLocks(context, "Zapp::Player");
	Disposable wakelockDisposable = playerEventHandler
		.getShouldHoldWakelock()
		.distinctUntilChanged()
		.subscribe(this::shouldHoldWakelockChanged);
	disposables.add(wakelockDisposable);

	// set listeners
	networkConnectionHelper.startListenForNetworkChanges(this::setStreamQualityByNetworkType);
}
 
Example #21
Source File: SimpleExoPlayer.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void setAudioAttributes(AudioAttributes audioAttributes) {
  setAudioAttributes(audioAttributes, /* handleAudioFocus= */ false);
}
 
Example #22
Source File: ListenerMux.java    From ExoMedia with Apache License 2.0 4 votes vote down vote up
@Override
public void onAudioAttributesChanged(EventTime eventTime, AudioAttributes audioAttributes) {
    if (analyticsListener != null) {
        analyticsListener.onAudioAttributesChanged(eventTime, audioAttributes);
    }
}
 
Example #23
Source File: SimpleExoPlayer.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
@Override
public AudioAttributes getAudioAttributes() {
  return audioAttributes;
}
 
Example #24
Source File: Player.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
/** Returns the attributes for audio playback. */
AudioAttributes getAudioAttributes();
 
Example #25
Source File: SimpleExoPlayer.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param context A {@link Context}.
 * @param renderersFactory A factory for creating {@link Renderer}s to be used by the instance.
 * @param trackSelector The {@link TrackSelector} that will be used by the instance.
 * @param loadControl The {@link LoadControl} that will be used by the instance.
 * @param drmSessionManager An optional {@link DrmSessionManager}. May be null if the instance
 *     will not be used for DRM protected playbacks.
 * @param bandwidthMeter The {@link BandwidthMeter} that will be used by the instance.
 * @param analyticsCollectorFactory A factory for creating the {@link AnalyticsCollector} that
 *     will collect and forward all player events.
 * @param clock The {@link Clock} that will be used by the instance. Should always be {@link
 *     Clock#DEFAULT}, unless the player is being used from a test.
 * @param looper The {@link Looper} which must be used for all calls to the player and which is
 *     used to call listeners on.
 */
protected SimpleExoPlayer(
    Context context,
    RenderersFactory renderersFactory,
    TrackSelector trackSelector,
    LoadControl loadControl,
    @Nullable DrmSessionManager<FrameworkMediaCrypto> drmSessionManager,
    BandwidthMeter bandwidthMeter,
    AnalyticsCollector.Factory analyticsCollectorFactory,
    Clock clock,
    Looper looper) {
  this.bandwidthMeter = bandwidthMeter;
  componentListener = new ComponentListener();
  videoListeners = new CopyOnWriteArraySet<>();
  audioListeners = new CopyOnWriteArraySet<>();
  textOutputs = new CopyOnWriteArraySet<>();
  metadataOutputs = new CopyOnWriteArraySet<>();
  videoDebugListeners = new CopyOnWriteArraySet<>();
  audioDebugListeners = new CopyOnWriteArraySet<>();
  eventHandler = new Handler(looper);
  renderers =
      renderersFactory.createRenderers(
          eventHandler,
          componentListener,
          componentListener,
          componentListener,
          componentListener,
          drmSessionManager);

  // Set initial values.
  audioVolume = 1;
  audioSessionId = C.AUDIO_SESSION_ID_UNSET;
  audioAttributes = AudioAttributes.DEFAULT;
  videoScalingMode = C.VIDEO_SCALING_MODE_DEFAULT;
  currentCues = Collections.emptyList();

  // Build the player and associated objects.
  player =
      new ExoPlayerImpl(renderers, trackSelector, loadControl, bandwidthMeter, clock, looper);
  analyticsCollector = analyticsCollectorFactory.createAnalyticsCollector(player, clock);
  addListener(analyticsCollector);
  addListener(componentListener);
  videoDebugListeners.add(analyticsCollector);
  videoListeners.add(analyticsCollector);
  audioDebugListeners.add(analyticsCollector);
  audioListeners.add(analyticsCollector);
  addMetadataOutput(analyticsCollector);
  bandwidthMeter.addEventListener(eventHandler, analyticsCollector);
  if (drmSessionManager instanceof DefaultDrmSessionManager) {
    ((DefaultDrmSessionManager) drmSessionManager).addListener(eventHandler, analyticsCollector);
  }
  audioFocusManager = new AudioFocusManager(context, componentListener);
}
 
Example #26
Source File: SimpleExoPlayer.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void setAudioAttributes(AudioAttributes audioAttributes) {
  setAudioAttributes(audioAttributes, /* handleAudioFocus= */ false);
}
 
Example #27
Source File: SimpleExoPlayer.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
@Override
public AudioAttributes getAudioAttributes() {
  return audioAttributes;
}
 
Example #28
Source File: Player.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
/** Returns the attributes for audio playback. */
AudioAttributes getAudioAttributes();
 
Example #29
Source File: SimpleExoPlayer.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param context A {@link Context}.
 * @param renderersFactory A factory for creating {@link Renderer}s to be used by the instance.
 * @param trackSelector The {@link TrackSelector} that will be used by the instance.
 * @param loadControl The {@link LoadControl} that will be used by the instance.
 * @param drmSessionManager An optional {@link DrmSessionManager}. May be null if the instance
 *     will not be used for DRM protected playbacks.
 * @param bandwidthMeter The {@link BandwidthMeter} that will be used by the instance.
 * @param analyticsCollectorFactory A factory for creating the {@link AnalyticsCollector} that
 *     will collect and forward all player events.
 * @param clock The {@link Clock} that will be used by the instance. Should always be {@link
 *     Clock#DEFAULT}, unless the player is being used from a test.
 * @param looper The {@link Looper} which must be used for all calls to the player and which is
 *     used to call listeners on.
 */
protected SimpleExoPlayer(
    Context context,
    RenderersFactory renderersFactory,
    TrackSelector trackSelector,
    LoadControl loadControl,
    @Nullable DrmSessionManager<FrameworkMediaCrypto> drmSessionManager,
    BandwidthMeter bandwidthMeter,
    AnalyticsCollector.Factory analyticsCollectorFactory,
    Clock clock,
    Looper looper) {
  this.bandwidthMeter = bandwidthMeter;
  componentListener = new ComponentListener();
  videoListeners = new CopyOnWriteArraySet<>();
  audioListeners = new CopyOnWriteArraySet<>();
  textOutputs = new CopyOnWriteArraySet<>();
  metadataOutputs = new CopyOnWriteArraySet<>();
  videoDebugListeners = new CopyOnWriteArraySet<>();
  audioDebugListeners = new CopyOnWriteArraySet<>();
  eventHandler = new Handler(looper);
  renderers =
      renderersFactory.createRenderers(
          eventHandler,
          componentListener,
          componentListener,
          componentListener,
          componentListener,
          drmSessionManager);

  // Set initial values.
  audioVolume = 1;
  audioSessionId = C.AUDIO_SESSION_ID_UNSET;
  audioAttributes = AudioAttributes.DEFAULT;
  videoScalingMode = C.VIDEO_SCALING_MODE_DEFAULT;
  currentCues = Collections.emptyList();

  // Build the player and associated objects.
  player =
      new ExoPlayerImpl(renderers, trackSelector, loadControl, bandwidthMeter, clock, looper);
  analyticsCollector = analyticsCollectorFactory.createAnalyticsCollector(player, clock);
  addListener(analyticsCollector);
  addListener(componentListener);
  videoDebugListeners.add(analyticsCollector);
  videoListeners.add(analyticsCollector);
  audioDebugListeners.add(analyticsCollector);
  audioListeners.add(analyticsCollector);
  addMetadataOutput(analyticsCollector);
  bandwidthMeter.addEventListener(eventHandler, analyticsCollector);
  if (drmSessionManager instanceof DefaultDrmSessionManager) {
    ((DefaultDrmSessionManager) drmSessionManager).addListener(eventHandler, analyticsCollector);
  }
  audioFocusManager = new AudioFocusManager(context, componentListener);
}
 
Example #30
Source File: AudioSlidePlayer.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private void play(final double progress, boolean earpiece) throws IOException {
  if (this.mediaPlayer != null) {
    return;
  }

  if (slide.getUri() == null) {
    throw new IOException("Slide has no URI!");
  }

  LoadControl loadControl = new DefaultLoadControl.Builder().setBufferDurationsMs(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE).createDefaultLoadControl();
  this.mediaPlayer           = ExoPlayerFactory.newSimpleInstance(context, new DefaultRenderersFactory(context), new DefaultTrackSelector(), loadControl);
  this.startTime             = System.currentTimeMillis();

  mediaPlayer.prepare(createMediaSource(slide.getUri()));
  mediaPlayer.setPlayWhenReady(true);
  mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
                                                    .setContentType(earpiece ? C.CONTENT_TYPE_SPEECH : C.CONTENT_TYPE_MUSIC)
                                                    .setUsage(earpiece ? C.USAGE_VOICE_COMMUNICATION : C.USAGE_MEDIA)
                                                    .build());
  mediaPlayer.addListener(new Player.EventListener() {

    boolean started = false;

    @Override
    public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
      Log.d(TAG, "onPlayerStateChanged(" + playWhenReady + ", " + playbackState + ")");
      switch (playbackState) {
        case Player.STATE_READY:
          Log.i(TAG, "onPrepared() " + mediaPlayer.getBufferedPercentage() + "% buffered");
          synchronized (AudioSlidePlayer.this) {
            if (mediaPlayer == null) return;

            if (started) {
              Log.d(TAG, "Already started. Ignoring.");
              return;
            }

            started = true;

            if (progress > 0) {
              mediaPlayer.seekTo((long) (mediaPlayer.getDuration() * progress));
            }

            sensorManager.registerListener(AudioSlidePlayer.this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);

            setPlaying(AudioSlidePlayer.this);
          }

          notifyOnStart();
          progressEventHandler.sendEmptyMessage(0);
          break;

        case Player.STATE_ENDED:
          Log.i(TAG, "onComplete");
          synchronized (AudioSlidePlayer.this) {
            mediaPlayer = null;

            sensorManager.unregisterListener(AudioSlidePlayer.this);

            if (wakeLock != null && wakeLock.isHeld()) {
              if (Build.VERSION.SDK_INT >= 21) {
                wakeLock.release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY);
              }
            }
          }

          notifyOnStop();
          progressEventHandler.removeMessages(0);
      }
    }

    @Override
    public void onPlayerError(ExoPlaybackException error) {
      Log.w(TAG, "MediaPlayer Error: " + error);

      Toast.makeText(context, R.string.AudioSlidePlayer_error_playing_audio, Toast.LENGTH_SHORT).show();

      synchronized (AudioSlidePlayer.this) {
        mediaPlayer = null;

        sensorManager.unregisterListener(AudioSlidePlayer.this);

        if (wakeLock != null && wakeLock.isHeld()) {
          if (Build.VERSION.SDK_INT >= 21) {
            wakeLock.release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY);
          }
        }
      }

      notifyOnStop();
      progressEventHandler.removeMessages(0);
    }
  });
}