免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4228 | 回复: 0
打印 上一主题 下一主题

Android中的音频播放(MediaPlayer和SoundPool) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-04-25 14:02 |只看该作者 |倒序浏览
Android中的音频播放(MediaPlayer和SoundPool)

Android中音频和视频的播放我们最先想到的就是MediaPlayer类了,该类提供了播放、暂停、停止、和重复播放等方法。该类位于android.media包下,详见API文档。其实除了这个类还有一个音乐播放类那就是SoundPool,这两个类各有不同分析一下便于大家理解

MediaPlayer:

   此类适合播放较大文件,此类文件应该存储在SD卡上,而不是在资源文件里,还有此类每次只能播放一个音频文件。

此类用法如下:

    1、从资源文件中播放

  1.               MediaPlayer   player  =   new MediaPlayer.create(this,R.raw.test);

  2.               player.stare();
复制代码
2、从文件系统播放
  1.    MediaPlayer   player  =   new MediaPlayer();

  2.               String  path   =  "/sdcard/test.mp3";

  3.                player.setDataSource(path);

  4.                player.prepare();

  5.                player.start();
复制代码
3、从网络播放

        (1)通过URI的方式:
  1. String path="http://**************.mp3";     //这里给一个歌曲的网络地址就行了

  2.                 Uri  uri  =  Uri.parse(path);

  3.                 MediaPlayer   player  =   new MediaPlayer.create(this,uri);

  4.                 player.start();
复制代码
(2)通过设置数据源的方式:
  1.     MediaPlayer   player  =   new MediaPlayer.create();

  2.              String path="http://**************.mp3";          //这里给一个歌曲的网络地址就行了

  3.              player.setDataSource(path);

  4.              player.prepare();

  5.              player.start();
复制代码
SoundPool:

  此类特点就是低延迟播放,适合播放实时音实现同时播放多个声音,如游戏中炸弹的爆炸音等小资源文件,此类音频比较适合放到资源文件夹 res/raw下和程序一起打成APK文件。

  用法如下:

  1.         SoundPool soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);

  2.         HashMap<Integer, Integer> soundPoolMap = new HashMap<Integer, Integer>();  

  3.         soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong1, 1));        

  4.         soundPoolMap.put(2, soundPool.load(this, R.raw.dingdong2, 2));      

  5.         public void playSound(int sound, int loop) {

  6.             AudioManager mgr = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);   

  7.             float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);   

  8.             float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);      

  9.            float volume = streamVolumeCurrent/streamVolumeMax;   

  10.            soundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1f);

  11.            //参数:1、Map中取值   2、当前音量     3、最大音量  4、优先级   5、重播次数   6、播放速度

  12. }   

  13.       this.playSound(1, 0);
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP