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);

1. SoundPool最大只能申请1M的内存空间,这就意味着我们只能用一些很短的声音片段,而不是用它来播放歌 曲或者做游戏背景音乐。

   2. SoundPool提供了pause和stop方法,但这些方法建议最好不要轻易使用,因为有些时候它们可能会使你的程序莫名其妙的终止。Android开发网建议使用这两个方法的时候尽可能多做测试工作,还有些朋友反映它们不会立即中止播放声音,而是把缓冲区里的数据播放完才会停下来,也许会多播放一秒钟。

   3. SoundPool的效率问题。其实SoundPool的效率在这些播放类中算是很好的了,这可能会影响用户体验。也许这不能管SoundPool本身,因为到了性能比较好的Droid中这个延迟就可以让人接受了。

注意soundPool播放的音源文件必须是ogg格式,否则可能会出现莫名其妙的问题