Android中的音频播放(MediaPlayer和SoundPool)
Android中音频和视频的播放我们最先想到的就是MediaPlayer类了,该类提供了播放、暂停、停止、和重复播放等方法。该类位于android.media包下,详见API文档。其实除了这个类还有一个音乐播放类那就是SoundPool,这两个类各有不同分析一下便于大家理解
MediaPlayer:
此类适合播放较大文件,此类文件应该存储在SD卡上,而不是在资源文件里,还有此类每次只能播放一个音频文件。
此类用法如下:
1、从资源文件中播放
MediaPlayer player = new MediaPlayer.create(this,R.raw.test);
player.stare();
2、从文件系统播放
MediaPlayer player = new MediaPlayer();
String path = "/sdcard/test.mp3";
player.setDataSource(path);
player.prepare();
player.start();
3、从网络播放
(1)通过URI的方式:
String path="http://**************.mp3"; //这里给一个歌曲的网络地址就行了
Uri uri = Uri.parse(path);
MediaPlayer player = new MediaPlayer.create(this,uri);
player.start();
(2)通过设置数据源的方式:
MediaPlayer player = new MediaPlayer.create();
String path="http://**************.mp3"; //这里给一个歌曲的网络地址就行了
player.setDataSource(path);
player.prepare();
player.start();
SoundPool:
此类特点就是低延迟播放,适合播放实时音实现同时播放多个声音,如游戏中炸弹的爆炸音等小资源文件,此类音频比较适合放到资源文件夹 res/raw下和程序一起打成APK文件。
用法如下:
SoundPool soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
HashMap<Integer, Integer> soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong1, 1));
soundPoolMap.put(2, soundPool.load(this, R.raw.dingdong2, 2));
public void playSound(int sound, int loop) {
AudioManager mgr = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent/streamVolumeMax;
soundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1f);
//参数:1、Map中取值 2、当前音量 3、最大音量 4、优先级 5、重播次数 6、播放速度
}
this.playSound(1, 0);
最新文章
- python迭代器
- JavaScript中的枚举
- maven常见问题问答
- AndroidStudio导入Android-PullToRefresh
- java中的循环
- javascript设计模式-抽象工厂模式
- 细说SQL 连接
- PHP字符串中的变量解析(+教你如何在PHP字符串中加入变量)
- CSS 布局总结——变宽度布局
- mongoDB3--mongoDB的基本操作。
- C语言 extern4 全局数组
- JS——操作内容、操作相关元素
- 设计模式总结(Java)—— 适配器模式
- Python爬虫02——贴吧图片爬虫V2.0
- 2018-2019 ICPC, NEERC, Southern Subregional Contest
- 用apache和tomcat搭建集群,实现负载均衡
- webpack入门(二)what is webpack
- git常用操作命令使用说明
- jQgrid学习笔记
- Tomcat8源码笔记(一)Lifecycle接口
热门文章
- Oracle - 位图索引的适用条件
- hdu1151 Air Raid
- mac 安装mysql 报错“ERROR 2002 (HY000): Can not connect to local MySQL server through socket &#39;/tmp/mysql.sock&#39; (2)” 解决办法
- N皇后//搜索入门
- cojs 奈特 题解报告
- JAVA:23种设计模式详解(转)2
- iOS 深入理解RunLoop
- Android 在Intent中传递接口
- csh与bash比较
- HDU 3038 How Many Answers Are Wrong 并查集带权路径压缩