Search in sources :

Example 21 with Callback

use of com.google.android.exoplayer2.source.MediaPeriod.Callback in project android-UniversalMusicPlayer by googlesamples.

the class LocalPlayback method play.

@Override
public void play(QueueItem item) {
    mPlayOnFocusGain = true;
    tryToGetAudioFocus();
    registerAudioNoisyReceiver();
    String mediaId = item.getDescription().getMediaId();
    boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
    if (mediaHasChanged) {
        mCurrentMediaId = mediaId;
    }
    if (mediaHasChanged || mExoPlayer == null) {
        // release everything except the player
        releaseResources(false);
        MediaMetadataCompat track = mMusicProvider.getMusic(MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));
        String source = track.getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE);
        if (source != null) {
            // Escape spaces for URLs
            source = source.replaceAll(" ", "%20");
        }
        if (mExoPlayer == null) {
            mExoPlayer = ExoPlayerFactory.newSimpleInstance(mContext, new DefaultTrackSelector(), new DefaultLoadControl());
            mExoPlayer.addListener(mEventListener);
        }
        // Android "O" makes much greater use of AudioAttributes, especially
        // with regards to AudioFocus. All of UAMP's tracks are music, but
        // if your content includes spoken word such as audiobooks or podcasts
        // then the content type should be set to CONTENT_TYPE_SPEECH for those
        // tracks.
        final AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(CONTENT_TYPE_MUSIC).setUsage(USAGE_MEDIA).build();
        mExoPlayer.setAudioAttributes(audioAttributes);
        // Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(mContext, Util.getUserAgent(mContext, "uamp"), null);
        // Produces Extractor instances for parsing the media data.
        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
        // The MediaSource represents the media to be played.
        MediaSource mediaSource = new ExtractorMediaSource(Uri.parse(source), dataSourceFactory, extractorsFactory, null, null);
        // Prepares media to play (happens on background thread) and triggers
        // {@code onPlayerStateChanged} callback when the stream is ready to play.
        mExoPlayer.prepare(mediaSource);
        // If we are streaming from the internet, we want to hold a
        // Wifi lock, which prevents the Wifi radio from going to
        // sleep while the song is playing.
        mWifiLock.acquire();
    }
    configurePlayerState();
}
Also used : DefaultExtractorsFactory(com.google.android.exoplayer2.extractor.DefaultExtractorsFactory) MediaMetadataCompat(android.support.v4.media.MediaMetadataCompat) AudioAttributes(com.google.android.exoplayer2.audio.AudioAttributes) ExtractorMediaSource(com.google.android.exoplayer2.source.ExtractorMediaSource) DefaultLoadControl(com.google.android.exoplayer2.DefaultLoadControl) DataSource(com.google.android.exoplayer2.upstream.DataSource) ExtractorMediaSource(com.google.android.exoplayer2.source.ExtractorMediaSource) MediaSource(com.google.android.exoplayer2.source.MediaSource) ExtractorsFactory(com.google.android.exoplayer2.extractor.ExtractorsFactory) DefaultExtractorsFactory(com.google.android.exoplayer2.extractor.DefaultExtractorsFactory) DefaultDataSourceFactory(com.google.android.exoplayer2.upstream.DefaultDataSourceFactory) DefaultTrackSelector(com.google.android.exoplayer2.trackselection.DefaultTrackSelector)

Example 22 with Callback

use of com.google.android.exoplayer2.source.MediaPeriod.Callback in project react-native-track-player by react-native-kit.

the class ExoPlayback method load.

@Override
public void load(Track track, Promise callback) {
    loadCallback = callback;
    Uri url = track.url;
    String userAgent = Util.getUserAgent(context, "react-native-track-player");
    DefaultHttpDataSourceFactory httpDataSourceFactory = new DefaultHttpDataSourceFactory(userAgent, null, DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS, DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS, true);
    DataSource.Factory factory = new DefaultDataSourceFactory(context, null, httpDataSourceFactory);
    MediaSource source;
    if (cacheMaxSize > 0 && !track.urlLocal) {
        File cacheDir = new File(context.getCacheDir(), "TrackPlayer");
        Cache cache = new SimpleCache(cacheDir, new LeastRecentlyUsedCacheEvictor(cacheMaxSize));
        factory = new CacheDataSourceFactory(cache, factory, 0, cacheMaxSize);
    }
    if (track.type == TrackType.DASH) {
        source = new DashMediaSource(url, factory, new DefaultDashChunkSource.Factory(factory), null, null);
    } else if (track.type == TrackType.HLS) {
        source = new HlsMediaSource(url, factory, null, null);
    } else if (track.type == TrackType.SMOOTH_STREAMING) {
        source = new SsMediaSource(url, factory, new DefaultSsChunkSource.Factory(factory), null, null);
    } else {
        source = new ExtractorMediaSource(url, factory, new DefaultExtractorsFactory(), null, null);
    }
    player.prepare(source);
}
Also used : DefaultExtractorsFactory(com.google.android.exoplayer2.extractor.DefaultExtractorsFactory) LeastRecentlyUsedCacheEvictor(com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor) DashMediaSource(com.google.android.exoplayer2.source.dash.DashMediaSource) CacheDataSourceFactory(com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory) DefaultHttpDataSourceFactory(com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory) DefaultDataSourceFactory(com.google.android.exoplayer2.upstream.DefaultDataSourceFactory) DefaultExtractorsFactory(com.google.android.exoplayer2.extractor.DefaultExtractorsFactory) ExtractorMediaSource(com.google.android.exoplayer2.source.ExtractorMediaSource) SsMediaSource(com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource) Uri(android.net.Uri) DataSource(com.google.android.exoplayer2.upstream.DataSource) DefaultHttpDataSource(com.google.android.exoplayer2.upstream.DefaultHttpDataSource) HlsMediaSource(com.google.android.exoplayer2.source.hls.HlsMediaSource) HlsMediaSource(com.google.android.exoplayer2.source.hls.HlsMediaSource) DashMediaSource(com.google.android.exoplayer2.source.dash.DashMediaSource) ExtractorMediaSource(com.google.android.exoplayer2.source.ExtractorMediaSource) MediaSource(com.google.android.exoplayer2.source.MediaSource) SsMediaSource(com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource) SimpleCache(com.google.android.exoplayer2.upstream.cache.SimpleCache) CacheDataSourceFactory(com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory) DefaultHttpDataSourceFactory(com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory) DefaultDataSourceFactory(com.google.android.exoplayer2.upstream.DefaultDataSourceFactory) File(java.io.File) Cache(com.google.android.exoplayer2.upstream.cache.Cache) SimpleCache(com.google.android.exoplayer2.upstream.cache.SimpleCache)

Example 23 with Callback

use of com.google.android.exoplayer2.source.MediaPeriod.Callback in project ExoPlayer by google.

the class AdTagLoader method handleTimelineOrPositionChanged.

private void handleTimelineOrPositionChanged() {
    @Nullable Player player = this.player;
    if (adsManager == null || player == null) {
        return;
    }
    if (!playingAd && !player.isPlayingAd()) {
        ensureSentContentCompleteIfAtEndOfStream();
        if (!sentContentComplete && !timeline.isEmpty()) {
            long positionMs = getContentPeriodPositionMs(player, timeline, period);
            timeline.getPeriod(player.getCurrentPeriodIndex(), period);
            int newAdGroupIndex = period.getAdGroupIndexForPositionUs(Util.msToUs(positionMs));
            if (newAdGroupIndex != C.INDEX_UNSET) {
                sentPendingContentPositionMs = false;
                pendingContentPositionMs = positionMs;
            }
        }
    }
    boolean wasPlayingAd = playingAd;
    int oldPlayingAdIndexInAdGroup = playingAdIndexInAdGroup;
    playingAd = player.isPlayingAd();
    playingAdIndexInAdGroup = playingAd ? player.getCurrentAdIndexInAdGroup() : C.INDEX_UNSET;
    boolean adFinished = wasPlayingAd && playingAdIndexInAdGroup != oldPlayingAdIndexInAdGroup;
    if (adFinished) {
        // IMA is waiting for the ad playback to finish so invoke the callback now.
        // Either CONTENT_RESUME_REQUESTED will be passed next, or playAd will be called again.
        @Nullable AdMediaInfo adMediaInfo = imaAdMediaInfo;
        if (adMediaInfo == null) {
            Log.w(TAG, "onEnded without ad media info");
        } else {
            @Nullable AdInfo adInfo = adInfoByAdMediaInfo.get(adMediaInfo);
            if (playingAdIndexInAdGroup == C.INDEX_UNSET || (adInfo != null && adInfo.adIndexInAdGroup < playingAdIndexInAdGroup)) {
                for (int i = 0; i < adCallbacks.size(); i++) {
                    adCallbacks.get(i).onEnded(adMediaInfo);
                }
                if (configuration.debugModeEnabled) {
                    Log.d(TAG, "VideoAdPlayerCallback.onEnded in onTimelineChanged/onPositionDiscontinuity");
                }
            }
        }
    }
    if (!sentContentComplete && !wasPlayingAd && playingAd && imaAdState == IMA_AD_STATE_NONE) {
        AdPlaybackState.AdGroup adGroup = adPlaybackState.getAdGroup(player.getCurrentAdGroupIndex());
        if (adGroup.timeUs == C.TIME_END_OF_SOURCE) {
            sendContentComplete();
        } else {
            // IMA hasn't called playAd yet, so fake the content position.
            fakeContentProgressElapsedRealtimeMs = SystemClock.elapsedRealtime();
            fakeContentProgressOffsetMs = Util.usToMs(adGroup.timeUs);
            if (fakeContentProgressOffsetMs == C.TIME_END_OF_SOURCE) {
                fakeContentProgressOffsetMs = contentDurationMs;
            }
        }
    }
}
Also used : Player(com.google.android.exoplayer2.Player) VideoAdPlayer(com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer) AdPlaybackState(com.google.android.exoplayer2.source.ads.AdPlaybackState) AdMediaInfo(com.google.ads.interactivemedia.v3.api.player.AdMediaInfo) Nullable(androidx.annotation.Nullable)

Example 24 with Callback

use of com.google.android.exoplayer2.source.MediaPeriod.Callback in project ExoPlayer by google.

the class ExoHostedTest method onStart.

// HostedTest implementation
@Override
public final void onStart(HostActivity host, Surface surface, FrameLayout overlayFrameLayout) {
    this.surface = surface;
    // Build the player.
    trackSelector = buildTrackSelector(host);
    player = buildExoPlayer(host, surface, trackSelector);
    player.play();
    player.addAnalyticsListener(this);
    player.addAnalyticsListener(new EventLogger(trackSelector, tag));
    // Schedule any pending actions.
    actionHandler = Clock.DEFAULT.createHandler(Util.getCurrentOrMainLooper(), /* callback= */
    null);
    if (pendingSchedule != null) {
        pendingSchedule.start(player, trackSelector, surface, actionHandler, /* callback= */
        null);
        pendingSchedule = null;
    }
    DrmSessionManager drmSessionManager = buildDrmSessionManager();
    player.setMediaSource(buildSource(host, drmSessionManager, overlayFrameLayout));
    player.prepare();
}
Also used : EventLogger(com.google.android.exoplayer2.util.EventLogger) DrmSessionManager(com.google.android.exoplayer2.drm.DrmSessionManager)

Example 25 with Callback

use of com.google.android.exoplayer2.source.MediaPeriod.Callback in project ExoPlayer by google.

the class MediaPeriodAsserts method prepareAndGetTrackGroups.

private static TrackGroupArray prepareAndGetTrackGroups(MediaPeriod mediaPeriod) {
    AtomicReference<TrackGroupArray> trackGroupArray = new AtomicReference<>();
    DummyMainThread testThread = new DummyMainThread();
    ConditionVariable preparedCondition = new ConditionVariable();
    testThread.runOnMainThread(() -> mediaPeriod.prepare(new Callback() {

        @Override
        public void onPrepared(MediaPeriod mediaPeriod) {
            trackGroupArray.set(mediaPeriod.getTrackGroups());
            preparedCondition.open();
        }

        @Override
        public void onContinueLoadingRequested(MediaPeriod source) {
        // Ignore.
        }
    }, /* positionUs= */
    0));
    try {
        preparedCondition.block();
    } catch (InterruptedException e) {
    // Ignore.
    }
    testThread.release();
    return trackGroupArray.get();
}
Also used : ConditionVariable(com.google.android.exoplayer2.util.ConditionVariable) Callback(com.google.android.exoplayer2.source.MediaPeriod.Callback) TrackGroupArray(com.google.android.exoplayer2.source.TrackGroupArray) AtomicReference(java.util.concurrent.atomic.AtomicReference) MediaPeriod(com.google.android.exoplayer2.source.MediaPeriod)

Aggregations

Test (org.junit.Test)23 ArrayList (java.util.ArrayList)10 HandlerThread (android.os.HandlerThread)9 Nullable (androidx.annotation.Nullable)9 FakeTimeline (com.google.android.exoplayer2.testutil.FakeTimeline)9 HandlerWrapper (com.google.android.exoplayer2.util.HandlerWrapper)9 FakeMediaSource (com.google.android.exoplayer2.testutil.FakeMediaSource)8 PlaybackParameters (com.google.android.exoplayer2.PlaybackParameters)7 Player (com.google.android.exoplayer2.Player)6 TestExoPlayerBuilder (com.google.android.exoplayer2.testutil.TestExoPlayerBuilder)6 ApplicationProvider (androidx.test.core.app.ApplicationProvider)5 AndroidJUnit4 (androidx.test.ext.junit.runners.AndroidJUnit4)5 ExoPlayer (com.google.android.exoplayer2.ExoPlayer)5 MediaSource (com.google.android.exoplayer2.source.MediaSource)5 Truth.assertThat (com.google.common.truth.Truth.assertThat)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 RunWith (org.junit.runner.RunWith)5 LoadEventInfo (com.google.android.exoplayer2.source.LoadEventInfo)4 ImmutableList (com.google.common.collect.ImmutableList)4 SurfaceTexture (android.graphics.SurfaceTexture)3