Android学习笔记–播放MP3

Linux大全评论472 views阅读模式

继续Android课程的学习。主要学习了在Android平台下面播放MP3音乐的技巧。通过今天的学习,为后面开发应用过程中为应用程序添加背景音乐,以及开发音乐播放器打下基础。

以下是我们从MediaPlayer类中得到的MediaPlayer对象的一个状态图

Android学习笔记–播放MP3

首先,我们打开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>  

企鹅博客
  • 本文由 发表于 2019年9月21日 04:42:52
  • 转载请务必保留本文链接:https://www.qieseo.com/171900.html

发表评论