xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/play"
android:text="播放"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/stop"
android:text="暂停"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/replay"
android:text="重新开始"/>
</LinearLayout>
MainActivity代码如下:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button play;
private Button stop;
private Button replay;
private MediaPlayer player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
replay = (Button) findViewById(R.id.replay);
play.setOnClickListener(this);
stop.setOnClickListener(this);
replay.setOnClickListener(this);
initVideo();
}
private void initVideo(){
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.music);
try {
player.prepare();// 同步
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.play:
if(!player.isPlaying()){
player.start();
}
break;
case R.id.stop:
if(player.isPlaying()){
player.pause();
}
break;
case R.id.replay:
if (!player.isPlaying()){
initVideo();
player.start();
//player.reset();
}else {
player.stop();
initVideo();
player.start();
}
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if(player!=null){
player.stop();
player.release();
}
}
}
本文地址:https://blog.csdn.net/weixin_44616286/article/details/107451668
如对本文有疑问, 点击进行留言回复!!
LongClick原理、上下文菜单原理、EditText长按弹窗原理、WebView长按弹窗自定义、修复WebView全选重复bug ———————————————— 版权声明:本文为CSDN博主「
JobScheduler 实现 特定时间,特定条件(系统空闲,电池电量,磁盘空间 ……)下执行任务
温习Android基础知识——《第一行代码(第三版)》读书笔记 Chapter 10 Service
网友评论