`
wjlgryx
  • 浏览: 298259 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Android平台SoundPool . MediaPlayer

阅读更多

Android平台中关于音频播放有以下两种方式: 
1. SoundPool —— 适合短促且对反应速度比较高的情况(游戏音效或按键声等)
2. MediaPlayer —— 适合比较长且对时间要求不高的情况

-------------------------------------------------------------------------------------------
SoundPool 

1. 创建一个SoundPool 
public SoundPool(int maxStream, int streamType, int srcQuality) 
maxStream —— 同时播放的流的最大数量
streamType —— 流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出)
srcQuality —— 采样率转化质量,当前无效果,使用0作为默认值

eg. 
SoundPool soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); 
创建了一个最多支持3个流同时播放的,类型标记为音乐的SoundPool。

2. 加载音频资源 
可以通过四种途径来记载一个音频资源:
int load(AssetFileDescriptor afd, int priority) 
通过一个AssetFileDescriptor对象
int load(Context context, int resId, int priority) 
通过一个资源ID
int load(String path, int priority) 
通过指定的路径加载
int load(FileDescriptor fd, long offset, long length, int priority) 
通过FileDescriptor加载

*API中指出,其中的priority参数目前没有效果,建议设置为1。 

一个SoundPool能同时管理多个音频,所以可以通过多次调用load函数来记载,如果记载成功将返回一个非0的soundID ,用于播放时指定特定的音频。

eg. 
int soundID1 = soundPool.load(this, R.raw.sound1, 1);
if(soundID1 ==0){
    // 记载失败
}else{
   // 加载成功
}
int soundID2 = soundPool.load(this, R.raw.sound2, 1);
...
 
这里加载了两个流,并分别记录了返回的soundID 。

需要注意的是, 
流的加载过程是一个将音频解压为原始16位PCM数据的过程,由一个后台线程来进行处理异步,所以初始化后不能立即播放,需要等待一点时间。

3. 播放控制 
有以下几个函数可用于控制播放:
final int play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) 
播放指定音频的音效,并返回一个streamID 。
        priority —— 流的优先级,值越大优先级高,影响当同时播放数量超出了最大支持数时SoundPool对该流的处理;
        loop —— 循环播放的次数,0为值播放一次,-1为无限循环,其他值为播放loop+1次(例如,3为一共播放4次).
        rate —— 播放的速率,范围0.5-2.0(0.5为一半速率,1.0为正常速率,2.0为两倍速率)
final void pause(int streamID) 
暂停指定播放流的音效(streamID 应通过play()返回)。
final void resume(int streamID) 
继续播放指定播放流的音效(streamID 应通过play()返回)。
final void stop(int streamID) 
终止指定播放流的音效(streamID 应通过play()返回)。

这里需要注意的是, 
1.play()函数传递的是一个load()返回的soundID——指向一个被记载的音频资源 ,如果播放成功则返回一个非0的streamID——指向一个成功播放的流 ;同一个soundID 可以通过多次调用play()而获得多个不同的streamID (只要不超出同时播放的最大数量);
2.pause()、resume()和stop()是针对播放流操作的,传递的是play()返回的streamID ;
3.play()中的priority参数,只在同时播放的流的数量超过了预先设定的最大数量是起作用,管理器将自动终止优先级低的播放流。如果存在多个同样优先级的流,再进一步根据其创建事件来处理,新创建的流的年龄是最小的,将被终止;
4.无论如何,程序退出时,手动终止播放并释放资源是必要的。

eg. 
//这里对soundID1的音效进行播放——优先级为0(最低),无限循环,正常速率。
int streamID = soundPool.play(soundID1 , 1.0, 1.0, 0, -1, 1.0);
if(streamID ==0){
    // 播放失败
}else{
    // 播放成功
}
...
// 暂停soundID1的播放
soundPool.pause(streamID );
... 
// 恢复soundID1的播放
soundPool.resume(streamID );
...
// 终止播放,记住循环为-1时必须手动停止
soundPool.stop(streamID );
 

*API中指出,即使使用无效的soundID /streamID (操作失败或指向无效的资源)来调用相关函数也不会导致错误,这样能减轻逻辑的处理。

4. 更多属性设置 
其实就是paly()中的一些参数的独立设置:
final void setLoop(int streamID, int loop) 
设置指定播放流的循环.
final void setVolume(int streamID, float leftVolume, float rightVolume) 
设置指定播放流的音量.
final void setPriority(int streamID, int priority) 
设置指定播放流的优先级,上面已说明priority的作用.
final void setRate(int streamID, float rate) 
设置指定播放流的速率,0.5-2.0.

5. 释放资源 
可操作的函数有:
final boolean unload(int soundID) 
卸载一个指定的音频资源.
final void release() 
释放SoundPool中的所有音频资源.

-汇总- 
一个SoundPool可以:
1.管理多个音频资源,通过load()函数,成功则返回非0的soundID;
2.同时播放多个音频,通过play()函数,成功则返回非0的streamID;
3.pause()、resume()和stop()等操作是针对streamID(播放流)的;
4.当设置为无限循环时,需要手动调用stop()来终止播放;
5.播放流的优先级(play()中的priority参数),只在同时播放数超过设定的最大数时起作用;
6.程序中不用考虑(play触发的)播放流的生命周期,无效的soundID/streamID不会导致程序错误。

-------------------------------------------------------------------------------------------

MediaPlayer 

你可以通过new或便捷的静态create函数组来创建一个MediaPlayer对象。

两种方式的比较: 
new MediaPlayer() 
1.成功调用后,MediaPlayer将处于Idle状态;
2.setDataSource提供了对String(path)、Uri和FileDescriptor格式的资源路径的支持;
3.后续需要手动调用prepare()才能进行播放。

MediaPlayer.create(...) 
1.成功调用后,MediaPlayer将处于Prepared状态;
2.create提供了对int(resID)和Uri格式的资源路径的支持;
3.无需(也不能)再次调用prepare()就能直接播放。

MediaPlayer的状态图:



 
椭圆 代表一个MediaPlayer可能处于的状态。
圆弧 代表(驱动对象状态转变的)播放控制的操作。
>>箭头有两种形态:
单箭 头代表同步函数的调用;
双箭 头代表异步的函数调用。

函数在不同状态下的有效性:

Method Name Valid Sates Invalid States Comments
attachAuxEffect {Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} {Idle, Error} This method must be called after setDataSource. Calling it does not change the object state.
getAudioSessionId any {} This method can be called in any state and calling it does not change the object state.
getCurrentPosition {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} {Error} Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the  Error  state.
getDuration {Prepared, Started, Paused, Stopped, PlaybackCompleted} {Idle, Initialized, Error} Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the  Error  state.
getVideoHeight {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} {Error} Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the  Error  state.
getVideoWidth {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} {Error} Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the  Error  state.
isPlaying {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} {Error} Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the  Error  state.
pause {Started, Paused} {Idle, Initialized, Prepared, Stopped, PlaybackCompleted, Error} Successful invoke of this method in a valid state transfers the object to the Paused   state. Calling this method in an invalid state transfers the object to theError   state.
prepare {Initialized, Stopped} {Idle, Prepared, Started, Paused, PlaybackCompleted, Error} Successful invoke of this method in a valid state transfers the object to the Prepared   state. Calling this method in an invalid state throws an IllegalStateException.
prepareAsync {Initialized, Stopped} {Idle, Prepared, Started, Paused, PlaybackCompleted, Error} Successful invoke of this method in a valid state transfers the object to the Preparing   state. Calling this method in an invalid state throws an IllegalStateException.
release any {} After  release() , the object is no longer available.
reset {Idle, Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, Error} {} After  reset() , the object is like being just created.
seekTo {Prepared, Started, Paused, PlaybackCompleted} {Idle, Initialized, Stopped, Error} Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the  Error  state.
setAudioSessionId {Idle} {Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, Error} This method must be called in idle state as the audio session ID must be known before calling setDataSource. Calling it does not change the object state.
setAudioStreamType {Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted} {Error} Successful invoke of this method does not change the state. In order for the target audio stream type to become effective, this method must be called before prepare() or prepareAsync().
setAuxEffectSendLevel any {} Calling this method does not change the object state.
setDataSource {Idle} {Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, Error} Successful invoke of this method in a valid state transfers the object to the Initialized   state. Calling this method in an invalid state throws an IllegalStateException.
setDisplay any {} This method can be called in any state and calling it does not change the object state.
setLooping {Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted} {Error} Successful invoke of this method in a valid state does not change the state. Calling this method in an invalid state transfers the object to the  Error  state.
isLooping any {} This method can be called in any state and calling it does not change the object state.
setOnBufferingUpdateListener any {} This method can be called in any state and calling it does not change the object state.
setOnCompletionListener any {} This method can be called in any state and calling it does not change the object state.
setOnErrorListener any {} This method can be called in any state and calling it does not change the object state.
setOnPreparedListener any {} This method can be called in any state and calling it does not change the object state.
setOnSeekCompleteListener any {} This method can be called in any state and calling it does not change the object state.
setScreenOnWhilePlaying any {} This method can be called in any state and calling it does not change the object state.
setVolume {Idle, Initialized, Stopped, Prepared, Started, Paused, PlaybackCompleted} {Error} Successful invoke of this method does not change the state.
setWakeMode any {} This method can be called in any state and calling it does not change the object state.
start {Prepared, Started, Paused, PlaybackCompleted} {Idle, Initialized, Stopped, Error} Successful invoke of this method in a valid state transfers the object to the Started   state. Calling this method in an invalid state transfers the object to theError   state.
stop {Prepared, Started, Stopped, Paused, PlaybackCompleted} {Idle, Initialized, Error} Successful invoke of this method in a valid state transfers the object to the Stopped   state. Calling this method in an invalid state transfers the object to theError   state.


要点: 
1.如果由于错误的操作(参照上图)导致MediaPlayer处于Error状态,可通过reset()函数来使其恢复到Idle状态,再重新执行setDataSource等初始化操作(ps:如果是通过create函数绑定资源ID创建的就郁闷了...); 
2.API中指出虽然reset后的MediaPlayer就像相当于新new的一样,但存在微妙的差异的: 
在这两种情况下播放器处于Idle状态,此时调用getCurrentPosition(), getDuration(),getVideoHeight(),getVideoWidth(), setAudioStreamType(int),setLooping(boolean), setVolume(float, float), pause(), start(), stop(),seekTo(int), prepare() 或 prepareAsync() 等函数都属与编程错误。当在MediaPlayer刚创建后调用这些函数,用户指定的OnErrorListener.onError() 回调函数不会被internal player engine(内部播放引擎)调用,并且播放器的状态依然未变;但如果是在调用reset() 函数之后,用户指定的OnErrorListener.onError() 回调函数将会被internal player engine(内部播放引擎)调用,并且播放器的状态将转变为Error(错误)状态。 
3.使用完毕后应该立即调用release()函数来释放资源,如果操作成功,MediaPlayer对象将处于End状态,此时无法再进行任何操作,除非重新创建MediaPlayer对象。 

更多的细节通过一个用new方式来创建的示例说明:

Java代码  收藏代码
  1. // 通过new创建后的player处于Idle状态  
  2.             MediaPlayer mp = new MediaPlayer();  
  3.              
  4.             if(mp==null){  
  5.                   // new创建有可能会返回null值,检测是好的习惯  
  6.                   return;  
  7.             }  
  8.              
  9.             // 设置资源路径,成功执行的话player将处于Initialized状态  
  10.             try {  
  11.                   mp.setDataSource("/sdcard/test.mp3"); // 直接传URL也是可以的,将自动处理缓冲  
  12.             } catch (IllegalArgumentException e) {  
  13.                   e.printStackTrace();  
  14.             } catch (IllegalStateException e) {  
  15.                   // 如果在非Idle状态下调用setDataSource就会导致该异常  
  16.                   e.printStackTrace();  
  17.             } catch (IOException e) {  
  18.                   e.printStackTrace();  
  19.             }  
  20.              
  21.             // 设置必要的监听器  
  22.             mp.setOnPreparedListener(new OnPreparedListener(){  
  23.   
  24.                   @Override  
  25.                   public void onPrepared(MediaPlayer mp) {  
  26.                         // 这时能确保player处于Prepared状态,触发start是最合适的  
  27.                         mp.start();  
  28.                   }  
  29.             });  
  30.             mp.setOnCompletionListener(new OnCompletionListener() {  
  31.                    
  32.                   @Override  
  33.                   public void onCompletion(MediaPlayer mp) {  
  34.                         // 正常播放结束,可以触发播放下一首  
  35.                   }  
  36.             });  
  37.             mp.setOnErrorListener(new OnErrorListener() {  
  38.                    
  39.                   @Override  
  40.                   public boolean onError(MediaPlayer mp, int what, intextra) {  
  41.                         // 操作错误或其他原因导致的错误会在这里被通知  
  42.                         return true;  
  43.                   }  
  44.             });  
  45.              
  46.             // 连接并加载资源  
  47.             try {  
  48.                   mp.prepare();  
  49. //                mp.prepareAsync() 这也是可以的,这是异步处理,上面的是同步处理,实际加载完毕以OnPreparedListener.onPrepared()为准。  
  50.             } catch (IllegalStateException e) {  
  51.                   e.printStackTrace();  
  52.             } catch (IOException e) {  
  53.                   e.printStackTrace();  
  54.             }  
  55. //          mp.start(); // 建议在OnPreparedListener.onPrepared()回调中触发该函数,特别是使用异步加载时  
  56.              
  57.             /** 
  58.              * ... 你的其他操作 ... 
  59.              */  
  60.              
  61.             // 终止播放并释放资源  
  62.             try{  
  63.                   mp.stop(); // 这是必要的,如果你设置了循环播放,否则程序退出了音乐仍在后台继续播...  
  64.                   mp.release();  
  65.             }catch(IllegalStateException e){  
  66.                   e.printStackTrace();  
  67.             }  

 

播放控制上基本与SoundPool相同有:
start()、pause()、stop()、seekTo()、setLooping()...

需要注意的是, 循环播放设置上与SoundPool不同,不能指定确定的循环次数,而是一个布尔值,指定是否循环播放...

分享到:
评论
1 楼 wjlgryx 2011-07-08  
  

相关推荐

    android安卓app音频播放方式 MediaPlayer与SoundPool的区别.zip

    android安卓app音频播放方式 MediaPlayer与SoundPool的区别.zip

    Android使用SoundPool实现播放音效

    SoundPool主要用于播放一些较短的声音片段,与MediaPlayer相比,SoundPool的优势在 于CPU资源占用量低和反应延迟小。另外,SoundPool还支持自行设置声音的品质、音量、播放比率等参数。 一般使用SoundPool播放声音的...

    android使用SoundPool播放音效的方法

    在Android开发中我们经常使用MediaPlayer来播放音频文件,但是MediaPlayer存在一些不足,例如:资源占用量较高、延迟时间较长、不支持多个音频同时播放等。这些缺点决定了MediaPlayer在某些场合的使用情况不会很理想...

    Android学习系列教程实例.pdf

    Android 学习文档总结 ................... 1 DevDiv 推荐资源 ........................ 2 Windows 8 ........................................................... 2 iOS .........................................

    android背景音乐音效,使用MediaPlayer、SoundPool实现

    android背景音乐、背景音效实例,其中大音频音乐播放使用MediaPlayer实现,小音频音效播放使用SoundPool实现

    炫舞吧 android 游戏开发

    mMediaPlayer = MediaPlayer.create(mContext, R.raw.bgmusic_3); /** 设置为循环播放 **/ mMediaPlayer.setLooping(true); mMediaPlayer.start(); } } }); builder.setNegativeButton("放弃", new ...

    Android使用SoundPool播放短音效

    对于Android播放一些简短音效,例如提示音,或者铃声,相对于使用MediaPlayer,SoundPool可以节省更多资源,并且可以同时播放多个音效,而且可以针对不同音效设置不同播放品质 实现 SoundPool的具体作用,就不再阐述...

    Android中播放声音的两种方法MediaPlayer 和SoundPool

    介绍android如果使用两个工具类进行声音播放 详见转载博客 http://blog.csdn.net/ygswine/article/details/17297571

    Android中SoundPool的使用步骤实例

    大家知道MediaPlayer占用的资源比较多,且不可以同时支持播放多个音频,所以我们有一种叫做SoundPool,比如我们常见的按键音或者是手机提示音,还比如我们在游戏的开发中会有大量的音效效果等,下边介绍一下她的用法...

    60个Android开发精典案例 Android软件源码.zip

    60个Android开发精典案例 Android软件源码: 2-1(Activity生命周期) 3-1(Button与点击监听器) 3-10-1(列表之ArrayAdapter适配) 3-10-2(列表之SimpleAdapter适配) 3-11(Dialog对话框) 3-12-5(Activity跳转与操作) 3-12...

    Android使用SoundPool实现播放音频

    最近做一个播放音频的小功能,使用...LinearLayout xmlns:android=http://schemas.android.com/apk/res/android xmlns:app=http://schemas.android.com/apk/res-auto xmlns:tools=http://schemas.android.com/tools

    Android播放系统提示音工具类

    这是一个播放Android系统提示音的工具类,可以调用SoundPool和MediaPlayer来播放提示音,使用起来简单方便.

    Android SoundPool实现简短小音效

    我们之前有用过MediaPlayer进行播放音频文件,但是当我们的应用程序需要经常的播放密集、短促的音效时,调用MediaPlayer则会占用系统的大量资源,且延时时间较长,不支持多个音频同时播放。这种简单的音乐的播放就...

    Android的音频与视频应用程序设计PPT

    (1)熟悉Android中播放声音的主要类SoundPool和MediaPlayer (2)熟悉Android中播放视频的主要类VideoView和SurfaceView (3)学会使用SoundPool类播放音频 (4)学会使用MediaPlayer类播放本地音频和网络音频 (5...

    Android多媒体应用使用SoundPool播放音频

    由于MediaPlayer占用资源较多,且不支持同时播放多个音频,所以Android还提供了另一个播放音频的类—–SoundPool。SoundPool即音频池,可以同时播放多个短小的音频,而且占用的资源较少。SoundPool适合在应用程序中...

    疯狂Android讲义.part2

    1.1.2 Android平台架构及特性 3 1.2 搭建Android开发环境 5 1.2.1 下载和安装Android SDK 5 1.2.2 安装Eclipse和ADT插件 7 1.3 Android常用开发工具的用法 10 1.3.1 创建、删除和浏览AVD 10 1.3.2 使用Android模拟器...

    疯狂Android讲义.part1

    1.1.2 Android平台架构及特性 3 1.2 搭建Android开发环境 5 1.2.1 下载和安装Android SDK 5 1.2.2 安装Eclipse和ADT插件 7 1.3 Android常用开发工具的用法 10 1.3.1 创建、删除和浏览AVD 10 1.3.2 使用Android模拟器...

    Android编程实现使用SoundPool播放音乐的方法

    本文实例讲述了Android编程实现使用SoundPool播放音乐的方法。分享给大家供大家参考,具体如下: 如果应用程序要播放密集、短促的音效,这时还用MediaPlayer就显得不合适了。MediaPlayer存在如下缺点: 1、资源占用...

    android实现小音频频繁播放

    android中多媒体文件(音乐和视频)的播放是用MediaPlayer方式是大家比较熟悉的,但是现在要来说一下另外一种音乐文件播放的方式SoundPool,相比较而言,用MediaPlayer来播放音乐的话,占用的系统资源是很多的,加载...

    android中音乐播放源码

    android中音乐播放源码,包括对MediaPlayer和SoundPool进行两种比较和两种播放的实现代码以及mp3 mid ogg资源 原文地址:http://blog.csdn.net/xiaominghimi/archive/2010/12/28/6101737.aspx

Global site tag (gtag.js) - Google Analytics