<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.moliying.a58_canvas_surfaceview.VideoActivity">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="@+id/surfaceView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放"
android:onClick="playClick"
android:id="@+id/button_play"
android:layout_below="@+id/surfaceView"
android:layout_alignStart="@+id/surfaceView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂停"
android:onClick="pauseClick"
android:id="@+id/button2"
android:layout_below="@+id/surfaceView"
android:layout_alignEnd="@+id/surfaceView" />
</RelativeLayout>
package com.moliying.a58_canvas_surfaceview;
import android.media.MediaPlayer;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import java.io.IOException;
public class VideoActivity extends AppCompatActivity implements SurfaceHolder.Callback{
private SurfaceView surfaceView;
private SurfaceHolder holder;
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
holder = surfaceView.getHolder();
holder.setFixedSize(320,200);//设置视频的分辩率,默认为原视频大小
holder.addCallback(this);
}
public void playClick(View view){
mp.start();
}
public void pauseClick(View view){
mp.pause();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mp = new MediaPlayer();
mp.setDisplay(holder); //把SurfaceHolder作为视频的显示
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)+"/14.mp4";
try {
mp.setDataSource(path);
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (null!=mp) {
mp.release();
}
}
}
不要忘了 清单权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />