最新项目中使用到了Android自带的Mediaplayer,所以在这里写了一个小Demo供大家参考使用。
Java代码部分
package club.anhe.surfaceviewdemo.surfaceviewdemo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import utils.CNTrace;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback{
MediaPlayer mMediaPlayer;
SurfaceView mSurface;
private int mPosition = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurface = (SurfaceView) findViewById(R.id.surface);
//mSurface.getHolder().setFixedSize(不要设置宽高,会自动拉伸播放,但不是我们所要的效果);
mSurface.getHolder().addCallback(this);
mSurface.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//为了和低版本兼容添加上了这一句
mMediaPlayer = new MediaPlayer();
}
private void play() {
try {
mMediaPlayer.reset();//重置为初始状态
mMediaPlay