1、基本使用
- MediaPlayer主要用于播放音频,没有提供图像输出界面,所以我们需要借助其他的 组件来显示MediaPlayer播放的图像输出,我们可以使用用SurfaceView
- 代码逻辑 ```json package com.xinhe.androidd;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";private MediaPlayer mediaPlayer;private SurfaceView surfaceView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);surfaceView = findViewById(R.id.surface);surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {@Overridepublic void surfaceCreated(SurfaceHolder holder) {Log.d(TAG, "surfaceCreated: "+holder.toString());}@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {Log.d(TAG, "surfaceCreated: format = " + format + ", width = " + width + ", height = " + height);}@Overridepublic void surfaceDestroyed(SurfaceHolder holder) {Log.d(TAG, "surfaceCreated: "+holder.toString());}});}public void play(View view) {try {mediaPlayer = new MediaPlayer();mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {@Overridepublic void onPrepared(MediaPlayer mp) {mediaPlayer.start();}});mediaPlayer.setDisplay(surfaceView.getHolder());mediaPlayer.setDataSource("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");mediaPlayer.prepareAsync();} catch (IOException e) {Log.e(TAG, "start: " + e.toString());e.printStackTrace();}}
}
- 布局文件```json<?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:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><SurfaceViewandroid:id="@+id/surface"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintTop_toTopOf="parent"android:layout_width="match_parent"android:layout_height="300dp"/><Buttonandroid:onClick="play"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintTop_toBottomOf="@id/surface"android:layout_width="match_parent"android:layout_height="wrap_content"/></androidx.constraintlayout.widget.ConstraintLayout>
