package com.example.mobile1931605008llx0702;import android.media.MediaPlayer;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity implements View.OnClickListener {//继承监听器类private TextView textView;private Button btnMainPlayer;private Button btnMainPause;private Button btnMainReplay;private Button btnMainStop;//控件对象private MediaPlayer mediaPlayer;//定义音乐播放对象@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();initMusic();}private void initMusic() {mediaPlayer = MediaPlayer.create(this, R.raw.zhoujiel_gaobaiqiqiu);//添加对象内容}private void initView() {textView = (TextView) findViewById(R.id.textView);btnMainPlayer = (Button) findViewById(R.id.btnMainPlayer);btnMainPause = (Button) findViewById(R.id.btnMainPause);btnMainReplay = (Button) findViewById(R.id.btnMainReplay);btnMainStop = (Button) findViewById(R.id.btnMainStop);//获取控件btnMainPause.setOnClickListener(this);//加入监听器btnMainPlayer.setOnClickListener(this);btnMainReplay.setOnClickListener(this);btnMainStop.setOnClickListener(this);}@Overridepublic void onClick(View v) {//监听器类switch (v.getId()) {//获取按钮idcase R.id.btnMainPlayer:mediaPlayer.start();//播放break;case R.id.btnMainPause:if (mediaPlayer != null && mediaPlayer.isPlaying())mediaPlayer.pause();//暂停break;case R.id.btnMainReplay:if (mediaPlayer != null) {//判断是否播放mediaPlayer.seekTo(0);//调整播放位置mediaPlayer.start();//开始播放}break;case R.id.btnMainStop:if (mediaPlayer != null) {mediaPlayer.stop();//停止,清除内容mediaPlayer=MediaPlayer.create(this,R.raw.zhoujiel_gaobaiqiqiu);//重新放进内容}break;}}}
Android-基础音乐播放
未经允许不得转载:爱站程序员基地 » Android-基础音乐播放