android studio播放器代码
时间: 2023-07-07 10:36:38 浏览: 90
以下是一个简单的 Android Studio 播放器代码示例:
```
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener {
private MediaPlayer mediaPlayer;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(holder);
mediaPlayer.setOnPreparedListener(MainActivity.this);
try {
mediaPlayer.setDataSource("your_mp4_video_url");
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
});
}
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
}
```
其中,`surfaceView` 用于展示视频画面,`surfaceHolder` 用于控制 `surfaceView`。在 `surfaceHolder` 的回调函数 `surfaceCreated()` 中,创建 `MediaPlayer` 对象,设置 `SurfaceHolder` 和数据源,调用 `prepareAsync()` 进行异步准备,等待 `onPrepared()` 回调,开始播放视频。在 `surfaceHolder` 的回调函数 `surfaceDestroyed()` 中,释放 `MediaPlayer` 对象。
阅读全文