Android写一个视频播放器
时间: 2023-11-10 20:22:43 浏览: 151
android实现视频播放器
5星 · 资源好评率100%
Android中实现视频播放器可以通过以下步骤:
1. 在布局文件中添加一个SurfaceView用来展示视频:
```
<SurfaceView
android:id="@+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 在Activity中获取SurfaceView并设置MediaPlayer:
```
public class VideoPlayerActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private MediaPlayer mediaPlayer;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
surfaceView = findViewById(R.id.surface_view);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mediaPlayer.setDisplay(holder);
try {
mediaPlayer.setDataSource("video_path");
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mediaPlayer.release();
}
}
```
3. 添加控制按钮来控制视频播放:
```
public void play(View view) {
mediaPlayer.start();
}
public void pause(View view) {
mediaPlayer.pause();
}
public void stop(View view) {
mediaPlayer.stop();
mediaPlayer.prepareAsync();
}
```
需要注意的是,视频播放器的具体实现可能因应用场景不同而有所差异,例如添加进度条、全屏播放等功能。
阅读全文