歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發音樂播放器

Android開發音樂播放器

日期:2017/3/1 11:16:31   编辑:Linux編程

音樂播放器中綜合了以下內容:

SeekBar、ListView、廣播接收者(以代碼的形式注冊Receiver)、系統服務、MediaPlayer

實現的功能:

1.暫停/播放、下一首/上一首,點擊某一首時播放

2.支持拖動進度條快進

3.列表排序

4.來電話時,停止播放,掛斷後繼續播放

5.可在後台播放

效果圖:

界面:

main.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView
  8. android:id="@+id/name"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. />
  12. <SeekBar
  13. android:id="@+id/seekBar"
  14. android:layout_width="fill_parent"
  15. android:layout_height="wrap_content"
  16. android:layout_marginBottom="5dp"
  17. />
  18. <LinearLayout
  19. android:layout_width="fill_parent"
  20. android:layout_height="wrap_content"
  21. android:layout_marginBottom="20dp"
  22. >
  23. <Button
  24. android:layout_width="40dp"
  25. android:layout_height="40dp"
  26. android:text="|◀"
  27. android:onClick="previous"
  28. />
  29. <Button
  30. android:id="@+id/pp"
  31. android:layout_width="40dp"
  32. android:layout_height="40dp"
  33. android:text="▶"
  34. android:onClick="pp"
  35. />
  36. <Button
  37. android:layout_width="40dp"
  38. android:layout_height="40dp"
  39. android:text="▶|"
  40. android:onClick="next"
  41. />
  42. </LinearLayout>
  43. <ListView
  44. android:id="@+id/list"
  45. android:layout_width="fill_parent"
  46. android:layout_height="fill_parent"
  47. />
  48. </LinearLayout>

item.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="fill_parent"
  5. android:layout_height="wrap_content"
  6. android:padding="10dp"
  7. >
  8. <TextView
  9. android:id="@+id/mName"
  10. android:layout_width="fill_parent"
  11. android:layout_height="wrap_content"
  12. android:textSize="15sp"
  13. />
  14. </LinearLayout>

MainActivity:

  1. package cn.test.audio;
  2. import java.io.File;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Map;
  8. import android.app.Activity;
  9. import android.content.BroadcastReceiver;
  10. import android.content.Context;
  11. import android.content.Intent;
  12. import android.content.IntentFilter;
  13. import android.media.MediaPlayer;
  14. import android.media.MediaPlayer.OnCompletionListener;
  15. import android.os.Bundle;
  16. import android.os.Environment;
  17. import android.os.Handler;
  18. import android.telephony.PhoneStateListener;
  19. import android.telephony.TelephonyManager;
  20. import android.view.View;
  21. import android.widget.AdapterView;
  22. import android.widget.Button;
  23. import android.widget.ListView;
  24. import android.widget.SeekBar;
  25. import android.widget.SimpleAdapter;
  26. import android.widget.TextView;
  27. import android.widget.AdapterView.OnItemClickListener;
  28. import android.widget.SeekBar.OnSeekBarChangeListener;
  29. public class MainActivity extends Activity {
  30. private TextView nameTextView;
  31. private SeekBar seekBar;
  32. private ListView listView;
  33. private List<Map<String, String>> data;
  34. private int current;
  35. private MediaPlayer player;
  36. private Handler handler = new Handler();
  37. private Button ppButton;
  38. private boolean isPause;
  39. private boolean isStartTrackingTouch;
  40. public void onCreate(Bundle savedInstanceState) {
  41. super.onCreate(savedInstanceState);
  42. setContentView(R.layout.main);
  43. nameTextView = (TextView) findViewById(R.id.name);
  44. seekBar = (SeekBar) findViewById(R.id.seekBar);
  45. listView = (ListView) findViewById(R.id.list);
  46. ppButton = (Button) findViewById(R.id.pp);
  47. //創建一個音樂播放器
  48. player = new MediaPlayer();
  49. //顯示音樂播放列表
  50. generateListView();
  51. //進度條監聽器
  52. seekBar.setOnSeekBarChangeListener(new MySeekBarListener());
  53. //播放器監聽器
  54. player.setOnCompletionListener(new MyPlayerListener());
  55. //意圖過濾器
  56. IntentFilter filter = new IntentFilter();
  57. //播出電話暫停音樂播放
  58. filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
  59. registerReceiver(new PhoneListener(), filter);
  60. //創建一個電話服務
  61. TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
  62. //監聽電話狀態,接電話時停止播放
  63. manager.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
  64. }
  65. /*
  66. * 監聽電話狀態
  67. */
  68. private final class MyPhoneStateListener extends PhoneStateListener {
  69. public void onCallStateChanged(int state, String incomingNumber) {
  70. pause();
  71. }
  72. }
  73. /*
  74. * 播放器監聽器
  75. */
  76. private final class MyPlayerListener implements OnCompletionListener {
  77. //歌曲播放完後自動播放下一首歌曲
  78. public void onCompletion(MediaPlayer mp) {
  79. next();
  80. }
  81. }
  82. /*
  83. * 下一首按鈕
  84. */
  85. public void next(View view) {
  86. next();
  87. }
  88. /*
  89. * 前一首按鈕
  90. */
  91. public void previous(View view) {
  92. previous();
  93. }
  94. /*
  95. * 播放前一首歌
  96. */
  97. private void previous() {
  98. current = current - 1 < 0 ? data.size() - 1 : current - 1;
  99. play();
  100. }
  101. /*
  102. * 播放下一首歌
  103. */
  104. private void next() {
  105. current = (current + 1) % data.size();
  106. play();
  107. }
  108. /*
  109. * 進度條監聽器
  110. */
  111. private final class MySeekBarListener implements OnSeekBarChangeListener {
  112. //移動觸發
  113. public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  114. }
  115. //起始觸發
  116. public void onStartTrackingTouch(SeekBar seekBar) {
  117. isStartTrackingTouch = true;
  118. }
  119. //結束觸發
  120. public void onStopTrackingTouch(SeekBar seekBar) {
  121. player.seekTo(seekBar.getProgress());
  122. isStartTrackingTouch = false;
  123. }
  124. }
  125. /*
  126. * 顯示音樂播放列表
  127. */
  128. private void generateListView() {
  129. List<File> list = new ArrayList<File>();
  130. //獲取sdcard中的所有歌曲
  131. findAll(Environment.getExternalStorageDirectory(), list);
  132. //播放列表進行排序,字符順序
  133. Collections.sort(list);
  134. data = new ArrayList<Map<String, String>>();
  135. for (File file : list) {
  136. Map<String, String> map = new HashMap<String, String>();
  137. map.put("name", file.getName());
  138. map.put("path", file.getAbsolutePath());
  139. data.add(map);
  140. }
  141. SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, new String[] { "name" }, new int[] { R.id.mName });
  142. listView.setAdapter(adapter);
  143. listView.setOnItemClickListener(new MyItemListener());
  144. }
  145. private final class MyItemListener implements OnItemClickListener {
  146. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  147. current = position;
  148. play();
  149. }
  150. }
  151. private void play() {
  152. try {
  153. //重播
  154. player.reset();
  155. //獲取歌曲路徑
  156. player.setDataSource(data.get(current).get("path"));
  157. //緩沖
  158. player.prepare();
  159. //開始播放
  160. player.start();
  161. //顯示歌名
  162. nameTextView.setText(data.get(current).get("name"));
  163. //設置進度條長度
  164. seekBar.setMax(player.getDuration());
  165. //播放按鈕樣式
  166. ppButton.setText("||");
  167. //發送一個Runnable, handler收到之後就會執行run()方法
  168. handler.post(new Runnable() {
  169. public void run() {
  170. // 更新進度條狀態
  171. if (!isStartTrackingTouch)
  172. seekBar.setProgress(player.getCurrentPosition());
  173. // 1秒之後再次發送
  174. handler.postDelayed(this, 1000);
  175. }
  176. });
  177. } catch (Exception e) {
  178. e.printStackTrace();
  179. }
  180. }
  181. /**
  182. * 查找文件路徑中所有mp3文件
  183. * @param file 要找的目錄
  184. * @param list 用來裝文件的List
  185. */
  186. private void findAll(File file, List<File> list) {
  187. File[] subFiles = file.listFiles();
  188. if (subFiles != null)
  189. for (File subFile : subFiles) {
  190. if (subFile.isFile() && subFile.getName().endsWith(".mp3"))
  191. list.add(subFile);
  192. else if (subFile.isDirectory())//如果是目錄
  193. findAll(subFile, list); //遞歸
  194. }
  195. }
  196. /*
  197. * 暫停/播放按鈕
  198. */
  199. public void pp(View view) {
  200. //默認從第一首歌曲開始播放
  201. if (!player.isPlaying() && !isPause) {
  202. play();
  203. return;
  204. }
  205. Button button = (Button) view;
  206. //暫停/播放按鈕
  207. if ("||".equals(button.getText())) {
  208. pause();
  209. button.setText("▶");
  210. } else {
  211. resume();
  212. button.setText("||");
  213. }
  214. }
  215. /*
  216. * 開始操作
  217. */
  218. private void resume() {
  219. if (isPause) {
  220. player.start();
  221. isPause = false;
  222. }
  223. }
  224. /*
  225. * 暫停操作
  226. */
  227. private void pause() {
  228. if (player != null && player.isPlaying()) {
  229. player.pause();
  230. isPause = true;
  231. }
  232. }
  233. /*
  234. * 收到廣播時暫停
  235. */
  236. private final class PhoneListener extends BroadcastReceiver {
  237. public void onReceive(Context context, Intent intent) {
  238. pause();
  239. }
  240. }
  241. /*
  242. * 恢復播放
  243. * @see android.app.Activity#onResume()
  244. */
  245. protected void onResume() {
  246. super.onResume();
  247. resume();
  248. }
  249. }

注冊權限:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="cn.itcast.audio"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <application android:icon="@drawable/icon" android:label="@string/app_name">
  7. <activity android:name=".MainActivity"
  8. android:label="@string/app_name">
  9. <intent-filter>
  10. <action android:name="android.intent.action.MAIN" />
  11. <category android:name="android.intent.category.LAUNCHER" />
  12. </intent-filter>
  13. </activity>
  14. </application>
  15. <uses-sdk android:minSdkVersion="8" />
  16. <!-- 監聽電話呼出 -->
  17. <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
  18. <!-- 監聽電話狀態改變 -->
  19. <uses-permission android:name="android.permission.READ_PHONE_STATE" />
  20. </manifest>
Copyright © Linux教程網 All Rights Reserved