zoukankan      html  css  js  c++  java
  • Android音频播放实例

    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);
  • 相关阅读:
    RocketMQ 概念
    CentOS7使用firewalld管理防火墙
    java应用启动报错Unable to access jarfile xxxxx.jar
    docker启动redis并设置密码
    sql优化整理(二)
    sql优化整理(一)
    dubbo配置的覆盖关系
    dubbo配置加载优先级
    ZooKeeper的数据模型
    leetcode104:permutations
  • 原文地址:https://www.cnblogs.com/newcaoguo/p/5802362.html
Copyright © 2011-2022 走看看