当前位置: 首页 > 编程日记 > 正文

实现音乐播放器

音乐播放器

   首先声明一下,本例是直接采用课本中范例122的方法。

效果图如下:

1、activity_main.xml布局

 1 //四个按钮
 2     <LinearLayout
 3         android:layout_width="fill_parent"
 4         android:layout_height="wrap_content"
 5         android:orientation="horizontal">
 6 // 上一首 
 7      <Button
 8          android:id="+id/previous"
 9          android:layout_width="wrap_content"
10          android:layout_height="fill_parent"
11          android:layout_weight="1"
12          android:text="上一首"
13       />
14 // 播放
15      <Button
16          android:id="+id/play"
17          android:layout_width="wrap_content"
18          android:layout_height="fill_parent"
19          android:layout_weight="1"
20          android:text="播放"
21       />
22 // 下一首
23      <Button
24          android:id="+id/next"
25          android:layout_width="wrap_content"
26          android:layout_height="fill_parent"
27          android:layout_weight="1"
28          android:text="下一首"
29       />
30 // 暂停 
31      <Button
32          android:id="+id/pause"
33          android:layout_width="wrap_content"
34          android:layout_height="fill_parent"
35          android:layout_weight="1"
36          android:text="暂停"
37       />
38      </LinearLayout>
View Code

2、MainAxtivity.java

  (1)定义四个按钮

  (2)绑定相应的监听对象

  (3)传递不同点击参数

代码如下:

 1 public class MainActivity extends Activity implements OnClickListener {
 2         //初始化控件
 3     private Button mBtnPrevious; // 上一首
 4     private Button mBtnPlay; // 播放
 5     private Button mBtnNext; // 下一首
 6     private Button mBtnPause; // 暂停
 7     private ComponentName component; // 用于启动服务
 8 
 9     public void onCreate(Bundle savedInstanceState) {
10         super.onCreate(savedInstanceState);
11         setContentView(R.layout.activity_main);
12         // 得到布局中的控件
13         findView();
14         // 绑定控件事件
15         setListener();
16     }
17 
18     // 得到布局中的控件
19     private void findView() {
20         component = new ComponentName(this, MusicService.class);
21         mBtnPrevious = (Button) findViewById(R.id.previous);
22         mBtnPlay = (Button) findViewById(R.id.play);
23         mBtnNext = (Button) findViewById(R.id.next);
24         mBtnPause = (Button) findViewById(R.id.pause);
25     }
26     // 绑定控件事件
27     private void setListener() {
28         mBtnPrevious.setOnClickListener(this);
29         mBtnPlay.setOnClickListener(this);
30         mBtnNext.setOnClickListener(this);
31         mBtnPause.setOnClickListener(this);
32     }
33     // 按钮点击事件响应
34     public void onClick(View v) {
35         // 如果点击前一首歌,就在intent中传递前一首歌参数
36         if (v == mBtnPrevious) {
37             Intent mIntent = new Intent(MusicService.PREVIOUS_ACTION);
38             mIntent.setComponent(component);
39             startService(mIntent);
40         // 如果点击前播放歌曲,就在intent中传递播放当前歌参数
41         } else if (v == mBtnPlay) {
42             Intent mIntent = new Intent(MusicService.PLAY_ACTION);
43             mIntent.setComponent(component);
44             startService(mIntent);
45         // 如果点击前一首歌,就在intent中传递下一首歌参数
46         } else if (v == mBtnNext) {
47             Intent mIntent = new Intent(MusicService.NEXT_ACTION);
48             mIntent.setComponent(component);
49             startService(mIntent);
50         // 如果点击前一首歌,就在intent中传递暂停首歌参数
51         } else {
52             Intent mIntent = new Intent(MusicService.PAUSE_ACTION);
53             mIntent.setComponent(component);
54             startService(mIntent);
55         }
56     }
57 }
主要代码

3、自定义Service

    (1)获取音频数据的字段名称

     (2) 初始化MediaPlayer对象

    (3)通过getContentResolver得到系统中所有音乐,只获取播放时间在10秒以上的音乐

    (4)onStart方法中判断得到的intent中的参数,调用相应方法

    (5)分别定义音乐的播放、暂停、前一首、下一首的实现内容

代码如下:

  1 //定义音乐服务类
  2 public class MusicService extends Service {
  3     // 定义需要显示的音乐的字段
  4     String[] mCursorCols = new String[] {
  5             "audio._id AS _id", // index must match IDCOLIDX below
  6             MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
  7             MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
  8             MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID,
  9             MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION };
 10     private MediaPlayer mMediaPlayer; // 声明播放器
 11     private Cursor mCursor; // 声明游标
 12     private int mPlayPosition = 0; // 当前播放的歌曲
 13 
 14     // 注册意图
 15     public static final String PLAY_ACTION = "com.wyl.music.PLAY_ACTION";
 16     public static final String PAUSE_ACTION = "com.wyl.music.PAUSE_ACTION";
 17     public static final String NEXT_ACTION = "com.wyl.music.NEXT_ACTION";
 18     public static final String PREVIOUS_ACTION = "com.wyl.music.PREVIOUS_ACTION";
 19 
 20     @Override
 21     public IBinder onBind(Intent arg0) {
 22         return null;
 23     }
 24 
 25     @Override
 26     public void onCreate() {
 27         super.onCreate();
 28         mMediaPlayer = new MediaPlayer();
 29         Uri MUSIC_URL = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;// 通过一个URI可以获取所有音频文件
 30         //默认大于10秒的可以看作是系统音乐
 31         mCursor = getContentResolver().query(MUSIC_URL, mCursorCols,
 32                 "duration > 10000", null, null);
 33     }
 34 
 35     @Override
 36     public void onStart(Intent intent, int startId) {
 37         super.onStart(intent, startId);
 38         // 根据不同的action,做不同的相应
 39         String action = intent.getAction();
 40         //播放
 41         if (action.equals(PLAY_ACTION)) {
 42             play();
 43         //暂停
 44         } else if (action.equals(PAUSE_ACTION)) {
 45             pause();
 46         //下一首
 47         } else if (action.equals(NEXT_ACTION)) {
 48             next();
 49         //前一首
 50         } else if (action.equals(PREVIOUS_ACTION)) {
 51             previous();
 52         }
 53     }
 54 
 55     // 播放音乐
 56     public void play() {
 57         //初始化音乐播放器
 58         inite();
 59     }
 60 
 61     // 暂停时,结束服务
 62     public void pause() {
 63         //暂停音乐播放
 64         stopSelf();
 65     }
 66 
 67     // 上一首
 68     public void previous() {
 69         //得到前一首的歌曲
 70         if (mPlayPosition == 0) {
 71             mPlayPosition = mCursor.getCount() - 1;
 72         } else {
 73             mPlayPosition--;
 74         }
 75         //开始播放
 76         inite();
 77     }
 78 
 79     // 下一首
 80     public void next() {
 81         //得到后一首歌曲
 82         if (mPlayPosition == mCursor.getCount() - 1) {
 83             mPlayPosition = 0;
 84         } else {
 85             mPlayPosition++;
 86         }
 87         //开始播放
 88         inite();
 89     }
 90 
 91     // 初始化播放器
 92     public void inite() {
 93         //充值MediaPlayer
 94         mMediaPlayer.reset();
 95         // 获取歌曲位置
 96         String dataSource = getDateByPosition(mCursor, mPlayPosition);
 97         // 歌曲信息
 98         String info = getInfoByPosition(mCursor, mPlayPosition);
 99         // 用Toast显示歌曲信息
100         Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT)
101                 .show();
102         try {
103             // 播放器绑定资源
104             mMediaPlayer.setDataSource(dataSource);
105             // 播放器准备
106             mMediaPlayer.prepare();
107             // 播放
108             mMediaPlayer.start();
109         } catch (IllegalArgumentException e1) {
110             e1.printStackTrace();
111         } catch (IllegalStateException e1) {
112             e1.printStackTrace();
113         } catch (IOException e1) {
114             e1.printStackTrace();
115         }
116     }
117 
118     // 根据位置来获取歌曲位置
119     public String getDateByPosition(Cursor c, int position) {
120         c.moveToPosition(position);
121         int dataColumn = c.getColumnIndex(MediaStore.Audio.Media.DATA);
122         String data = c.getString(dataColumn);
123         return data;
124     }
125 
126     // 获取当前播放歌曲演唱者及歌名
127     public String getInfoByPosition(Cursor c, int position) {
128         c.moveToPosition(position);
129         int titleColumn = c.getColumnIndex(MediaStore.Audio.Media.TITLE);
130         int artistColumn = c.getColumnIndex(MediaStore.Audio.Media.ARTIST);
131         String info = c.getString(artistColumn) + " "
132                 + c.getString(titleColumn);
133         return info;
134 
135     }
136 
137     // 服务结束时要释放MediaPlayer
138     public void onDestroy() {
139         super.onDestroy();
140         mMediaPlayer.release();
141     }
142 }
音乐服务类

播放器完成!

转载于:https://www.cnblogs.com/j0820/p/4620104.html

相关文章:

学习ASP.NET MVC系列 - 还有比这更简炼的吗?把复杂的事情变简单了,贡献啊!...

转自学习ASP.NET MVC系列&#xff1a; 学习ASP.NET MVC(一)——我的第一个ASP.NET MVC应用程序 学习ASP.NET MVC(二)——我的第一个ASP.NET MVC 控制器 学习ASP.NET MVC(三)——我的第一个ASP.NET MVC 视图 学习ASP.NET MVC(四)——我的第一个ASP.NET MVC 实体对象 学习ASP.NET…

微信小程序开通腾讯云开发实践流程附详细图解

微信小程序开发交流qq群 173683895 云开发流程&#xff1a; 1.关联账户 关联腾讯云账号与微信公众号平台账号。前往关联账号时&#xff0c;请选择微信公众号。错误关联账号请在腾讯云账号中心重新绑定。 已关联账号 2.安装开发者工具 下载与安装客户端微信开发者工具并使…

github组织存储库使用_为什么我不使用您的GitHub存储库

github组织存储库使用by Sam Westreich, PhD由Sam Westreich博士 为什么我不使用您的GitHub存储库 (Why I’m not using your GitHub repository) As a bioinformatician, I reside in an interesting middle ground between developers and end users. My background trainin…

PHP导入excel到mysql数据库完整代码附效果图

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 1.新建一个数据库 ImportXlsx 并在里面添加表名 IsXlsx. 2.下载 phpExcel 插件 点击下载 3.导入文件和xlsx 。 4.获取xlsx表的对象并存入数据库 效果图&#xff1a; PHP 实现 demo <?phph…

黑马程序员—易混淆的知识

------- android培训、java培训、期待与您交流&#xff01; ---------- String和StringBuffer类区别1.String 是定长的例如&#xff1a;String s1"abc";s1"egf";StringBuffer类:是变成字符串&#xff0c;因为它具有&#xff08;buffer&#xff09;缓冲区&a…

简谈 Java 中的泛型通配符

很好的一篇文章https://zhuanlan.zhihu.com/p/26681625 转载于:https://www.cnblogs.com/hihtml5/p/6978651.html

播客#47:劳伦斯·布拉德福德

On todays episode, I interview Laurence Bradford. Shes the creator of the LearnToCodeWith.me blog and podcast, and the Newbie Coder Warehouse Facebook group.在今天的一集中&#xff0c;我采访了劳伦斯布拉德福德。 她是LearnToCodeWith.me博客和播客以及Newbie Cod…

如何使用 DBCC MEMORYSTATUS 命令来监视 SQL Server 2005 中的内存使用情况

https://technet.microsoft.com/en-us/solutionaccelerators/dd537566.aspx 注意&#xff1a;这篇文章是由无人工介入的微软自动的机器翻译软件翻译完成。微软很高兴能同时提供给您由人工翻译的和由机器翻译的文章, 以使您能使用您的语言访问所有的知识库文章。然而由机器翻译的…

{code:-1,error:`QcloudSecretId`不能为空,请确保 SDK 配置已正确初始化}解决方法

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 微信小程序云开发登录报错&#xff1a;{"code":-1,"error":"QcloudSecretId不能为空&#xff0c;请确保 SDK 配置已正确初始化"} 遇到这个错误的原因是&#xff1a;腾讯不…

[转载] Tmux 速成教程:技巧和调整

原文: http://blog.jobbole.com/87584/ 决定从 screen 转向 tmux 了, 非常喜欢 tmux 的窗格功能. 简介 有些开发者经常要使用终端控制台工作&#xff0c;导致最终打开了过多的标签页。如果你也是他们当中的一员&#xff0c;或者你正在实践结对编程&#xff0c;那么我推荐你读一…

css在兼容模式下无法引用_如何在CSS中使用深色模式

css在兼容模式下无法引用by Frank Lmmer由FrankLmmer 如何在CSS中使用深色模式 (How to get dark mode working with CSS) I have been playing around with MacOS Mojave’s dark mode lately. It’s not 100% pleasing to my eyes, yet. But it’s especially useful when n…

COJ 0995 WZJ的数据结构(负五)区间操作

WZJ的数据结构&#xff08;负五&#xff09;难度级别&#xff1a;C&#xff1b; 运行时间限制&#xff1a;1000ms&#xff1b; 运行空间限制&#xff1a;262144KB&#xff1b; 代码长度限制&#xff1a;2000000B 试题描述请你设计一个数据结构&#xff0c;完成以下功能&#xf…

接入网易云信IM即时通讯的微信小程序聊天室

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 接入流程&#xff1a; 初次接触网易云通信IM服务&#xff0c;您可以通过以下产品介绍文档了解我们的产品功能、相关概念、业务限制&#xff1a; 产品简介主要功能帐号集成与登录接口及业务限制 1. 创建…

vue颜色选择器_如何制作? Vue的颜色选择器!

vue颜色选择器by ZAYDEK由ZAYDEK 如何制作&#xff1f; Vue的颜色选择器&#xff01; (How to make a ? color picker with Vue!) 注意&#xff1a;颜色看起来可能比实际颜色更可爱&#xff01; (Caution: colors may appear cuter than they are!) Before I get to the arti…

centos7中使用yum安装tomcat以及它的启动、停止、重启

centos7中使用yum安装tomcat 介绍 Apache Tomcat是用于提供Java应用程序的Web服务器和servlet容器。 Tomcat是Apache Software Foundation发布的Java Servlet和JavaServer Pages技术的开源实现。 本教程介绍在CentOS 7服务器上使用yum进行Tomcat 7的基本安装和一些配置。请注意…

JS 数组A有数组B的数据就删除

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 创建了两个数组&#xff0c;并且封装了一个函数以供调用。 var arr1 [a,b,c,d],arr2 [a,c,d,f]; this.arrayWeightRemoval(arr1,arr2); //返回结果 [b] ;// 数据去重this.arrayWeightRemoval functio…

PL/SQL Developer的调试存储过程

学会使用PL/SQL Developer的调试功能&#xff0c;对于编写复杂的存储过程&#xff0c;包&#xff0c;funtion...非常有帮助&#xff0c;所以今晚学习了一下&#xff1a; &#xff08;1&#xff09;在sp里设置断点。 &#xff08;2&#xff09;点击TEST. (3) Debug-->Start. …

graphql_普通英语GraphQL指南

graphqlby Luis Aguilar路易斯阿吉拉尔(Luis Aguilar) 普通英语GraphQL指南 (A Guide to GraphQL in Plain English) 您需要了解的最新流行语正在席卷API开发领域。 (All you need to know about the latest buzzword that’s taking the API development scene by storm.) TL…

第1课第4.4节_Android硬件访问服务编写HAL代码

android应用如何访问C库 - 落魄影子 - 博客频道 - CSDN.NET http://blog.csdn.net/ab198604/article/details/51249303 Android硬件访问服务框架代码编写 - 落魄影子 - 博客频道 - CSDN.NET http://blog.csdn.net/ab198604/article/details/51397586 4 编写HAL代码 源码下载方…

Android新版NDK环境配置(免Cygwin)

本菜鸟在查阅了很多文章&#xff0c;又是去折腾cygwin之类的&#xff0c;虽然可以编译出so文件&#xff0c;但运行项目却有很多问题。当发现最新的ndk不需要cygwin的时候&#xff0c;跪了&#xff08;orz&#xff09;。 现在进入正题。 使用工具&#xff1a; adt-bundle-window…

小程序获取用户的操作轨迹日志

微信小程序开发交流qq群 173683895 花费了两天时间&#xff0c;修改过数次&#xff0c;终于把这个功能封装成了一个独立的工具。 任何小程序都可在不修改原代码的情况下直接镶入使用&#xff01;&#xff01;&#xff01; 步骤&#xff1a; 1. 在小程序 app.js 的平级目录…

paypal提现软件_PayPal软件工程师生命中的一天

paypal提现软件Find out what a normal day is like for a PayPal software engineer.找出PayPal软件工程师的正常日子。 Shruti Kapoor shares what she does and shows off some of the PayPal campus in San Jose, California.Shruti Kapoor分享了她的工作&#xff0c;并展…

关于IOS的蓝牙(转)

关于IOS的蓝牙 首先&#xff0c;你要了解你的目的是什么&#xff0c;一般的IOS蓝牙开发有以下三种目的&#xff1a; 1. IOS设备和IOS设备之间交互 好消息是&#xff1a;ios6.0可以把iPhone手机当从设备了&#xff0c;可以两台iPhone通过蓝牙通信传数据了&#xff0c;有点类似sp…

JavaSE--jdom解析之bom

参考&#xff1a;http://www.cnblogs.com/findumars/p/3620078.html 1 org.jdom2.input.JDOMParseException: Error on line 1: Content is not allowed in prolog. 2 13:15:55,821 [main] ERROR SajtSvrImpl:182 - 未知&#xff1a;org.jdom2.input.JDOMParseException: Error…

JS数组去重,JS根据数组里面的对象属性值去重

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 微信小程序开发交流qq群 173683895 js数组简单去重 var arr1 [1, 2, 3, 4, 5, 6, 3, 4, 3];function arrayUnique1(arr) {var arr1 [], obj {};for (var i 0, elem; (elem arr[i]) ! null; i) {i…

git 设置有效目录_如何有效使用Git

git 设置有效目录The code was working yesterday but today it is not该代码昨天有效&#xff0c;但今天却没有 The code got deleted代码被删除 A weird bug has been introduced suddenly and no-one knows how突然引入了一个奇怪的错误&#xff0c;没人知道如何 If you hav…

C\C++宏大全

一、标准预定义宏The standard predefined macros are specified by the relevant language standards, so they are available with all compilers that implement those standards. Older compilers may not provide all of them. Their names all start with double undersc…

POJ 3630 Phone List

题目大意:给n个字符串,问是否有一个是另一个的前缀思路:把n个字符串插到trie里,然后判断就好&#xff0c;注意一个长字符串覆盖另一个短字符串和短字符串匹配长字符串的区别 1 #include<iostream>2 #include<cstring>3 #include<cstdio>4 #define maxn 10000…

微信小程序地图标记点,点击标记点显示详细信息源码加效果图

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 效果图&#xff1a; 实现代码: <!-- <text>{{markers[id].placeName}}</text> --> <block wx:if{{isshow}}><map id"map" longitude"114.048410" latit…

如何仅使用HTML和JavaScript构建简单的URL缩短器

by Palash Bauri由Palash Bauri 如何仅使用HTML和JavaScript构建简单的URL缩短器 (How to build a simple URL shortener with just HTML and JavaScript) You might have used a URL shortener before, such as bit.ly, goo.gl. They are useful for shortening long URLs so…