Andriod Studio实现简易音乐播放盒
提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用
文章目录
前言
随着android手机的普及和一些小游戏的流行,再加上近年来智能汽车的发展,android的开发也愈发变得重要起来了,一个绚丽的、酷酷的音乐盒也成为我们锻炼自己对安卓知识掌握情况的一个重要体现,为了符合更多的人审美,设计界面的清晰、美观、大方且操作方便已经是一个非常重要的体验因素。
一、项目结果展示
大家在使用手机音乐播放器的时候,都会看到“上一首”、“暂停 / 播放”、“重新开始”、“下一首”这几个按钮。。
二、具体代码实现
1.main.xml
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="180dp">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_weight="1"
android:gravity="center"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:textColor="#9C27B0"
android:textSize="25sp"
android:text="歌曲名"/>
<TextView
android:id="@+id/author"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="歌手名"
android:textSize="25sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="90dp"
android:orientation="horizontal">
<ImageButton
android:id="@+id/pre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/pre" />
<ImageButton
android:id="@+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/play"/>
<ImageButton
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/stop"/>
<ImageButton
android:id="@+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/next" />
</LinearLayout>
</LinearLayout>
xt
2.MainActivity.java
代码如下:
package com.example.Hzf;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Date;
public class MainActivity extends Activity implements View.OnClickListener {
// 获取界面中显示歌曲标题、作者文本框
TextView title, author , currentTime , totalTime;
// 播放/暂停按钮、停止按钮
ImageButton play, stop;
//上一首、下一首按钮
ImageButton previous, next;
ProgressBar progressBar;
ActivityReceiver activityReceiver;
static final String CTL_ACTION = "org.zzw.action.CTL_ACTION";
static final String UPDATE_ACTION = "org.zzw.action.UPDATE_ACTION";
// 定义音乐的播放状态,0x11代表没有播放;0x12代表正在播放;0x13代表暂停
int status = 0x11;
String[] titleStrs = {"Legends Never Die","约定", "心愿", "美丽新世界"};
String[] authorStrs = {"英雄联盟","周蕙", "4个女生", "伍佰"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取程序界面界面中的按钮控件
play = findViewById(R.id.play);
stop = findViewById(R.id.stop);
previous = findViewById(R.id.previous);
next = findViewById(R.id.next);
//获取文本组件
title = findViewById(R.id.title);
author = findViewById(R.id.author);
//获取进度条控制组件
progressBar = findViewById(R.id.progressBar);
currentTime = findViewById(R.id.currentTime);
totalTime = findViewById(R.id.totalTime);
// 为按钮的单击事件添加监听器
play.setOnClickListener(this);
stop.setOnClickListener(this);
previous.setOnClickListener(this);
next.setOnClickListener(this);
//获取进度条控件
activityReceiver = new ActivityReceiver();
// 创建IntentFilter
IntentFilter filter = new IntentFilter();
// 指定BroadcastReceiver监听的Action
filter.addAction(UPDATE_ACTION);
// 注册BroadcastReceiver
registerReceiver(activityReceiver, filter);
// 启动后台Service
startService(new Intent(this, MusicService.class));
}
public class ActivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int update = intent.getIntExtra("update",-1);
int current = intent.getIntExtra("current", -1);
int now = intent.getIntExtra("currentTime",-1);
int total = intent.getIntExtra("totalTime",-1);
if (current >= 0){
title.setText(titleStrs[current]);
author.setText(authorStrs[current]);
}
if (total >= 0) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss", Locale.CHINA);
Date date = new Date(total);
String formatTime = simpleDateFormat.format(date);
totalTime.setText(formatTime);
}
if (now >= 0) {
double process = ((double)now / total) * 100;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss", Locale.CHINA);
Date date = new Date(now);
String formatTime = simpleDateFormat.format(date);
progressBar.setProgress((int) process);
currentTime.setText(formatTime);
}
switch (update){
case 0x11:
play.setImageResource(R.drawable.play);
status = 0x11;
break;
case 0x12:
play.setImageResource(R.drawable.pause);
status = 0x12;
break;
case 0x13:
play.setImageResource(R.drawable.play);
status = 0x13;
break;
}
}
}
@Override
public void onClick(View source)
{
// 创建Intent
Intent intent = new Intent(CTL_ACTION);
switch (source.getId())
{
// 按下播放/暂停按钮
case R.id.play:
intent.putExtra("control", 1);
break;
// 按下停止按钮
case R.id.stop:
intent.putExtra("control", 2);
break;
// 按下上一首
case R.id.previous:
intent.putExtra("control", 3);
break;
// 按下下一首
case R.id.next:
intent.putExtra("control", 4);
break;
}
// 发送广播,将被Service组件中的BroadcastReceiver接收到
sendBroadcast(intent);
}
}
3.MusicService.java
package com.example.Hzf;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
public class MusicService extends Service {
MyReceiver serviceReceiver;
AssetManager am;
Thread processThread;
static final String[] musics = { "legendsneverdie.mp3","promise.mp3", "wish.mp3", "beautiful.mp3" };
MediaPlayer mPlayer;
// 当前的状态,0x11代表没有播放;0x12代表正在播放;0x13代表暂停
int status = 0x11;
// 记录当前正在播放的音乐
int current = 0;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
am = getAssets(); //获取附件管理器
// 创建BroadcastReceiver
serviceReceiver = new MyReceiver();
// 创建IntentFilter
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.CTL_ACTION);
registerReceiver(serviceReceiver, filter);
mPlayer = new MediaPlayer();
// 为MediaPlayer播放完成事件绑定监听器
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.d("MusicService", "歌曲播放完毕");
current++;
if (current >= 4)
{
current = 0;
}
//发送广播通知Activity更改文本框
Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
sendIntent.putExtra("current", current);
// 发送广播,将被Activity组件中的BroadcastReceiver接收到
sendBroadcast(sendIntent);
// 准备并播放音乐
prepareAndPlay(musics[current]);
}
});
processThread = new Thread(() -> {
while (true)
{
// 如果是播放状态
if (status == 0x12)
{
try {
// 休眠一秒
Thread.sleep(1000);
// 给主线程发送广播
Intent sendIntent1 = new Intent(MainActivity.UPDATE_ACTION);
// 当前进度
sendIntent1.putExtra("currentTime", mPlayer.getCurrentPosition());
// 总进度
sendIntent1.putExtra("totalTime", mPlayer.getDuration());
// 发送广播,将被Activity组件中的BroadcastReceiver接收到
sendBroadcast(sendIntent1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
processThread.start();
}
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(final Context context, Intent intent)
{
// 获取Intent中的Control状态
int control = intent.getIntExtra("control", -1);
switch (control)
{
// 播放或暂停
case 1:
// 原来处于没有播放状态
if (status == 0x11)
{
// 准备并播放音乐
prepareAndPlay(musics[current]);
status = 0x12;
}
// 原来处于播放状态
else if (status == 0x12)
{
// 暂停
mPlayer.pause();
// 改变为暂停状态
status = 0x13;
}
// 原来处于暂停状态
else if (status == 0x13)
{
// 播放
mPlayer.start();
// 改变状态
status = 0x12;
}
break;
//停止声音
case 2:
if (status == 0x12 || status == 0x13) {
mPlayer.stop();
status = 0x11;
}
break;
//上一首
case 3:
// 如果原来正在播放或暂停
if (status == 0x12 || status == 0x13) {
mPlayer.stop();
if (current - 1 < 0) {
current = musics.length - 1;
} else {
current--;
}
prepareAndPlay(musics[current]);
status = 0x12;
}
break;
//下一首
case 4:
if (status == 0x12 || status == 0x13) {
mPlayer.stop();
if (current + 1 >= musics.length) {
current = 0;
} else {
current++;
}
prepareAndPlay(musics[current]);
status = 0x12;
}
break;
}
// 广播通知Activity更改图标、文本框
Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
sendIntent.putExtra("update", status);
sendIntent.putExtra("current", current);
// 发送广播,将被Activity组件中的BroadcastReceiver接收到
sendBroadcast(sendIntent);
}
}
private void prepareAndPlay(String music)
{
try
{
// 打开指定音乐文件
AssetFileDescriptor afd = am.openFd(music);
mPlayer.reset();
// 使用MediaPlayer加载指定的声音文件。
mPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
// 准备声音
mPlayer.prepare();
// 播放
mPlayer.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
三、源码仓库
总结
通过对android手机平台音乐播放器的开发,是我对android音乐播放器系统的整体设计有了一个更加深入的了解,对于整个流程也有了一个更加清晰的认识,开发音乐播放器要抓住开发的核心部分,音乐播放器大体上由播放主界面、播放列表、菜单、播放设置、歌曲搜索这六大部分组成,虽然这次的开发只做了一些基本的功能,但我会继续学习,之后会在这个初具规模的简单播放器上添加新的功能,向着QQ音乐靠拢,争取尽快写出一个正儿八经的播放器。