歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android學習筆記--播放MP3

Android學習筆記--播放MP3

日期:2017/3/1 11:16:02   编辑:Linux編程
繼續Android課程的學習。主要學習了在Android平台下面播放MP3音樂的技巧。通過今天的學習,為後面開發應用過程中為應用程序添加背景音樂,以及開發音樂播放器打下基礎。

以下是我們從MediaPlayer類中得到的MediaPlayer對象的一個狀態圖


首先,我們打開Android開發文檔Dev Guide標簽,找到Audio and Video開發頁。在該頁中為我們詳細介紹了使用類MediaPlayer播放音樂的方法。總結內容如下:

播放文件類型:

  • raw resource:主要存儲在應用程序的資源文件中,例如:背景音樂。
  • file system resource:處於Android文件系統中的音樂文件。
  • networking stream:網絡流音樂文件

開發方法:

關於raw resource開發

  1. 將音樂文件存儲在應用程序中的 /res/raw目錄中。Eclipse插件將會對文件進行編譯,可以通過R類中的資源標識符引用該音樂文件。
  2. 通過MediaPlayer類中的靜態方法create(context,resid)創建播放器(在調用creat()方法時候,系統會自動調用prepare()方法,是的播放器對象進入Prepared狀態)。當要播放文件的時候調用start()方法,則播放器對象進入如上圖的Started狀態。
  3. 當需要停止播放文件的時候調用stop()方法(當調用stop()後,播放器對象將轉入Stopped狀態),如果用戶在播放器處於Stopped狀態後,下次還想播放該文件,則首先需要通過調用prepare()方法將程序轉入Prepared狀態,隨後調用start()可以繼續播放文件。
  4. 當需要暫停播放文件的時候調用pause()方法,需要繼續播放調用start()方法即可。

關於 file system resource 和 networking stream文件開發

  1. 使用new 方法創建播放器,播放器對象處於Idle狀態;
  2. 使用setDataSource()設置文件本地路徑或文件的網絡路徑,播放器對象處於Initialized狀態;
  3. 調用 prepare()方法,進入Prepared狀態;
  4. 調用start()方法,進入Started狀態;
  5. 有關stop()以及pause()方法的使用和raw resource文件開發類似;
下面是一個測試例子,對上面講述的內容進行簡單的應用:
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" android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <RadioGroup android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content">
  6. <RadioButton android:id="@+id/rawRadioButton"
  7. android:text="raw" android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"></RadioButton>
  9. <RadioButton android:id="@+id/fileRadioButton"
  10. android:text="file" android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"></RadioButton>
  12. </RadioGroup>
  13. <Button android:id="@+id/startButton" android:layout_width="wrap_content"
  14. android:layout_height="wrap_content" android:text="start" />
  15. <Button android:id="@+id/pauseButton" android:layout_width="wrap_content"
  16. android:layout_height="wrap_content" android:text="pause" />
  17. <Button android:id="@+id/stopButton" android:layout_width="wrap_content"
  18. android:layout_height="wrap_content" android:text="stop" />
  19. </LinearLayout>
Copyright © Linux教程網 All Rights Reserved