package com.example.zyc.surfaceview;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SurfaceView surfaceView;
private File file;
private Button playButton;
private Button pauseButton;
private Button stopButton;
private boolean isPlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//實現各種控件
mediaPlayer = new MediaPlayer();
surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
playButton = (Button)findViewById(R.id.play);
pauseButton = (Button)findViewById(R.id.pause);
stopButton = (Button)findViewById(R.id.stop);
//初始化一些變量
isPlay = false;
file = new File(Environment.getExternalStorageDirectory().getPath()+"/aa.mp4");
pauseButton.setEnabled(false);
//surfaceView.setBackgroundResource(R.drawable.bg);
//實現三個按鈕的方法
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.reset(); //重置MediaPlay對象
try {
mediaPlayer.setDataSource(file.getAbsolutePath()); //讀取視頻文件地址
}catch(IOException e){
e.printStackTrace();
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(surfaceView.getHolder()); //將視頻畫面輸出到surface上
//確保視屏加載完畢才能夠播放
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
Log.i("TAG","准備完畢開始播放");
mediaPlayer.start(); //開始播放
pauseButton.setText("暫停"); //pause此時為暫停
pauseButton.setEnabled(true); //pause按鈕此時可用
isPlay = true;
}
});
try {
mediaPlayer.prepareAsync(); //讓視頻加載,加載完後自動執行onPrepared()
}catch(Exception e){
Log.i("TAG","加載發生錯誤");
}
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isPlay == true) {
pauseButton.setText("繼續");
mediaPlayer.pause();
isPlay = false;
} else {
mediaPlayer.start();
pauseButton.setText("暫停");
isPlay = true;
}
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isPlay==true){
mediaPlayer.stop();
Toast.makeText(MainActivity.this,"已停止",Toast.LENGTH_LONG).show();
pauseButton.setEnabled(false);
}
}
});
}
@Override
protected void onDestroy() {
if(isPlay==true){
mediaPlayer.stop();
}
mediaPlayer.release();
super.onDestroy();
}
}
以上是代碼 用來播放小的MP4文件是沒有什麼問題。 但是我後來用來嘗試播放一個1.4G的MP4文件後報出TransactionTooLargeException異常,原因是.prepareAsync()不能加載視頻文件(文件過於大,不能被加載),我想解決,但是沒有什麼思路,不知道有什麼辦法。
http://lovelease.iteye.com/blog/2105616