一、 基本介绍
简单的音乐播放器实例, 提供播放、停止、暂停、退出音乐操作。 先由Activity 实现,再引出由Service(本地Service)实现。
二、Acitivity实现
1. 布局文件
<?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="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Play"
android:onClick="playMusic"/>
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Stop"
android:onClick="stopMusic"/>
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Pause"
android:onClick="pauseMusic"/>
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Exit"
android:onClick="exitMusic"/>
</LinearLayout>
2. Activity中实现音乐操作
package com.example.musicplayer;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private MediaPlayer mPlayer = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void playMusic(View view) {
log("playMusic");
if (mPlayer == null) {
mPlayer = MediaPlayer.create(this, R.raw.simple_music);
}
mPlayer.start();
log("playMusic done");
}
public void stopMusic(View view) {
log("stopMusic");
if (mPlayer != null) {
mPlayer.stop();
mPlayer.reset(); //重置(进度)
mPlayer.release(); //释放资源
mPlayer = null;
log("stopMusic done");
}
}