surfaceview 加载Assets下的视频,设置循环播放并取消声音
surfaceviewj加载视频的几种方法
1、加载 assets
2、加载本地文件下
3、加载网络音视频 setDataSource("http://juejin.cn/ok.mp3")
try {
// 创建MediaPlayer对象
player = new MediaPlayer();
// 设置SurfaceView自己不管理缓冲区
getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// 设置播放时打开屏幕
getHolder().setKeepScreenOn(true);
getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
player.reset();
try {
MyLog.e("surfaceCreated:" + GUIDE_VIDEOS + File.separator + assetsName);
AssetFileDescriptor mDescriptor = getContext().getAssets().openFd(GUIDE_VIDEOS + File.separator + assetsName);
player.setDataSource(mDescriptor.getFileDescriptor(), mDescriptor.getStartOffset(), mDescriptor.getLength());
// player.setDataSource(new File(MyApplication.getApplication().guideVideosPath, "v_guide.mp4").getAbsolutePath());
player.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置播放声音类型
player.setVolume(0,0);
player.setLooping(true);
player.setDisplay(getHolder());
// player.prepare();
player.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
MyLog.e("surfaceChanged:" + format + " :" + width + ":" + height);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
MyLog.e("surfaceDestroyed:" + holder.toString());
// if (isShowing)
// playerRelease();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
MyLog.d(" onPrepared : " + System.currentTimeMillis() + " :" + isShowing);
prepared = true;
// player.setPlaybackParams(player.getPlaybackParams().setSpeed(0.8f));
player.start();
}
});
player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
MyLog.e("what:"+what+":"+extra);
// player.reset();
// try {
// AssetFileDescriptor mDescriptor = getContext().getAssets().openFd(GUIDE_VIDEOS + File.separator + assetsName);
// player.setDataSource(mDescriptor.getFileDescriptor(), mDescriptor.getStartOffset(), mDescriptor.getLength());
// player.prepareAsync();
// } catch (IOException e) {
// e.printStackTrace();
// }
return false;
}
});
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
MyLog.d(" onCompletion=" + System.currentTimeMillis());
// postDelayed(new Runnable() {
// @Override
// public void run() {
// if (isShowing) {
// player.seekTo(0);
// player.start();
// }
// }
// }, 2000);
}
});
} catch (Exception e) {
e.printStackTrace();
MyLog.e("e:" + e.getMessage());
}