android: 视频: 用ExoPlayer播放在线视频
一,安装第三方库
库地址:
https://mvnrepository.com/artifact/androidx.media3/media3-exoplayer
在build.gradle中添加:
implementation "androidx.media3:media3-exoplayer:1.7.1"
implementation "androidx.media3:media3-common:1.7.1"
implementation "androidx.media3:media3-ui:1.7.1"
然后点击 Sync Now 链接
说明:
如果media3-exoplayer的库和exoplayer-core的库同时出现在build.gradle,会引发类型错误
二,代码
xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.Video1Activity">
<Button
android:id="@+id/openButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="播放网络视频"
tools:ignore="MissingConstraints" />
<androidx.media3.ui.PlayerView
android:id="@+id/player_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:show_buffering="when_playing"
app:show_shuffle_button="true"/>
</androidx.constraintlayout.widget.ConstraintLayout>
java
package com.example.okdemo1.activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import com.example.okdemo1.R;
import androidx.media3.common.MediaItem;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;
public class Video1Activity extends AppCompatActivity {
private ExoPlayer mPlayer;
private PlayerView playerView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video1);
//得到player view
playerView = findViewById(R.id.player_view);
mPlayer = new ExoPlayer.Builder(this).build();
playerView.setPlayer(mPlayer);
//点击按钮事件
Button button2 = findViewById(R.id.openButton);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("https://docs.evostream.com/sample_content/assets/bun33s.mp4");
playVideo(uri);
}
});
}
@Override
protected void onDestroy() {
mPlayer.release();
super.onDestroy();
}
// 播放视频
private void playVideo(Uri uri) {
DataSource.Factory factory = new DefaultDataSource.Factory(this);
// 创建指定地址的媒体对象
MediaItem videoItem = new MediaItem.Builder().setUri(uri).build();
mPlayer.setMediaItem(videoItem);
mPlayer.prepare(); // 播放器准备就绪
mPlayer.prepare();
mPlayer.play(); // 播放器开始播放
}
}
三,测试效果:
浙公网安备 33010602011771号