以下是一个使用ExoPlayer直接播放原始mp4(h264)片段的示例代码:
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
public class MainActivity extends AppCompatActivity {
private SimpleExoPlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.simple_exo_player_view);
// 创建一个默认的TrackSelector
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
// 创建ExoPlayer实例
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
// 将player关联到simpleExoPlayerView
simpleExoPlayerView.setPlayer(player);
// 准备要播放的视频
Uri videoUri = Uri.parse("your_mp4_video_url_here");
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this, "ExoPlayerDemo");
ExtractorMediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.setExtractorsFactory(new DefaultExtractorsFactory())
.createMediaSource(videoUri);
// 准备播放器
player.prepare(videoSource);
// 开始播放
player.setPlayWhenReady(true);
}
@Override
protected void onPause() {
super.onPause();
// 暂停播放
player.setPlayWhenReady(false);
// 释放播放器资源
player.release();
}
}
在上面的代码中,你需要将your_mp4_video_url_here
替换为你想要播放的mp4视频的URL。此代码使用了ExoPlayer库来处理视频播放。它创建了一个ExoPlayer实例,将其关联到SimpleExoPlayerView上,并准备要播放的视频源。在onPause
方法中,暂停播放并释放播放器资源。
请确保在项目的build.gradle
文件中添加了ExoPlayer库的依赖:
implementation 'com.google.android.exoplayer:exoplayer:2.X.X'
其中2.X.X
是你想要使用的ExoPlayer版本号。
希望这可以解决你的问题!