您的位置:首页 > 移动开发 > Android开发

Android中的音频播放(MediaPlayer和SoundPool)

2012-03-02 14:36 387 查看
Android中的音频播放(MediaPlayer和SoundPool)

http://bbs.chinaunix.net/thread-2309035-1-1.html

Android中的音频播放(MediaPlayer和SoundPool)http://bbs.chinaunix.net/thread-2309035-1-1.html

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: