Android简易实战教程--第三十五话《音乐播放》

时间:2020-12-11 20:00:32

已经好几天不更新博客了,今天轻松一点模拟个简单的“音乐播放器”。1分钟看完~

整个简单布局,加几个控制按钮:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" > <Button
android:id="@+id/play"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Play" /> <Button
android:id="@+id/pause"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Pause" /> <Button
android:id="@+id/stop"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Stop" /> </LinearLayout>

主活动代码也是soeasy:

package com.example.playaudiotest;

import java.io.File;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity implements OnClickListener { private Button play; private Button pause; private Button stop; private MediaPlayer mediaPlayer = new MediaPlayer(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
initMediaPlayer();
} private void initMediaPlayer() {
try {
File file = new File(Environment.getExternalStorageDirectory(), "music.mp3");
//设置播放路径,资源
mediaPlayer.setDataSource(file.getPath());
//播放前的准备工作
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
} @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
if (!mediaPlayer.isPlaying()) {
//开始播放
mediaPlayer.start();
}
break;
case R.id.pause:
if (mediaPlayer.isPlaying()) {
//暂停播放
mediaPlayer.pause();
}
break;
case R.id.stop:
if (mediaPlayer.isPlaying()) {
//Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().
//重置,如果调用此方法,必须人为的再次调用设置资源、准备方法
mediaPlayer.reset();
initMediaPlayer();
}
break;
default:
break;
}
} @Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
} }

需要重点关注的是mediaPlayer.reset();方法。看文档说明:

Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().


大致意思是:重置,如果调用此方法,必须人为的再次调用设置资源、准备方法

既然调用了就在此调用initMediaPlayer();

运行,开始听音乐吧~~

对于MediaPlayer这个类的一些认识,可以参考Android初级教程的一篇博客:MediaPlayer的生命周期