播放音频
在res/asset目录下存储音频文件,这里处理多个点击事件,选择实现监听接口,在布局文件的view中要指定点击处理的方法。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer mediaPlayer=new MediaPlayer();;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPlayer();
}
private void initPlayer() {
AssetManager assets = getAssets();
try {
AssetFileDescriptor fd = assets.openFd("exam.mp3");
mediaPlayer.setDataSource(fd);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
mediaPlayer.start();
break;
case R.id.button2:
mediaPlayer.pause();
break;
case R.id.button3:
//这里重置mediaplayer后要重新加载资源
mediaPlayer.reset();
initPlayer();
break;
}
}
}
播放视频
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/"+R.raw.video);
videoView = (VideoView) findViewById(R.id.video);
videoView.setVideoURI(uri);
}
@Override
public void onClick(View v) {
Log.d("mes", "onClick: "+v.getId());
switch (v.getId()) {
case R.id.play:
if(!videoView.isPlaying()){
videoView.start();
videoView.requestFocus();
}
break;
case R.id.pause:
if(videoView.isPlaying())videoView.pause();
break;
case R.id.reset:
if(videoView.isPlaying())videoView.resume();
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
videoView.suspend();
}
}