Android-------Soundpool 及 musicolayer

开发 Android 软件中我们可能经常需播放多媒体声音文件,一般使用 MediaPlayer 类但该类占用资源较多,对于游戏等应用可能不是很适合, SoundPool 类在 SDK android.media.SoundPool ,顾名思义是声音池的意思。主要播放一些较短的声音片段,可以从程序的资源或文件系统加载,相对于 MediaPlayer 类可以做到使用较少的 CPU 资源和较短的反应延迟。

            SoundPool和其他声音播放类相比,其特点是可以自行设置声音的品质、音量、播放比率等参等。并且它可以同时管理多个音频流,每个流都有独自的ID,对某个音频流的管理都是通过ID进行的。


SoundPool基本使用方法:
              1. 创建一个SoundPool 
                 创建一个SoundPool对象:new SoundPool(int maxStreams, int streamType, int srcQuality);

                public SoundPool(int maxStream, int streamType, int srcQuality) 
                maxStream —— 同时播放的流的最大数量 
                  streamType —— 流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出) 
                  srcQuality —— 采样率转化质量,当前无效果,使用0作为默认值 
                  eg. 
                    SoundPool soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);

                       创建了一个最多支持3个流同时播放的,类型标记为音乐的SoundPool。
          2、 从资源或者文件载入音频流: load(Context context, int resId, int priority);

                    soundpool的加载: 
                       int  load(Context context, int resId, int priority)  //从APK资源载入 
                       int  load(FileDescriptor fd, long offset, long length, int priority)  //从FileDescriptor对象载入 
                       int  load(AssetFileDescriptor afd, int priority)  //从Asset对象载入 
                       int  load(String path, int priority)  //从完整文件路径名载入 
                                  最后一个参数为优先级。

                         一般把多个声音放到HashMap中去,比如 
                         soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); 
                         soundPoolMap = new HashMap<Integer, Integer>();   
                         soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong, 1));
          3、  播放声音play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate);

                     play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) ,

                       其中leftVolume和rightVolume表示左右音量,

                            priority表示优先级,

                            loop表示循环次数,

                           rate表示速率,如  //速率最低0.5最高为2,1代表正常速度 
                    sp.play(soundId, 1, 1, 0, 0, 1); 
                    而停止则可以使用 pause(int streamID) 方法,这里的streamID和soundID均在构造SoundPool类的

                    第一个参数中指明了总数量,而id从0开始。


布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" 
    >

     <TextView   
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="歌曲名:"/>  
        
    <TextView   
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="blueflawer.mp3"/>  
        
    <Button   
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="播放"  
        android:id="@+id/play_pause"/>  
        
    <Button   
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="重置"  
        android:id="@+id/reset"/> 
    
    <SeekBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/seekbar" 
        />
    

</LinearLayout>

Activity:



public class MyPlayerActivity extends Activity {  
    private Button play_pause, reset;  
    private SeekBar seekbar;  
    private boolean ifplay = false;  
    private MediaPlayer player = null;  
    private String musicName = "blueflawer.mp3";  
    private boolean iffirst = false;  
    private Timer mTimer;    
    private TimerTask mTimerTask;   
    private boolean isChanging=false;//互斥变量,防止定时器与SeekBar拖动时进度冲突   
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        player = new MediaPlayer();  
        findViews();// 各组件  
    }  
  
    private void findViews() {  
        play_pause = (Button) findViewById(R.id.play_pause);  
        reset = (Button) findViewById(R.id.reset);  
        play_pause.setOnClickListener(new MyClick());  
        reset.setOnClickListener(new MyClick());  
  
        seekbar = (SeekBar) findViewById(R.id.seekbar);  
        seekbar.setOnSeekBarChangeListener(new MySeekbar());  
    }  
  
    class MyClick implements OnClickListener {  
        public void onClick(View v) {  
            File file = new File(Environment.getExternalStorageDirectory(),  
                    musicName);  
            // 判断有没有要播放的文件  
            if (file.exists()) {  
                switch (v.getId()) {  
                case R.id.play_pause:  
                    if (player != null && !ifplay) {  
                        play_pause.setText("暂停");  
                        if (!iffirst) {  
                            player.reset();  
                            try {  
                                player.setDataSource(file.getAbsolutePath());  
                                player.prepare();// 准备  
  
                            } catch (IllegalArgumentException e) {  
                                e.printStackTrace();  
                            } catch (IllegalStateException e) {  
                                e.printStackTrace();  
                            } catch (IOException e) {  
                                e.printStackTrace();  
                            }  
                            seekbar.setMax(player.getDuration());//设置进度条                            
                            mTimer = new Timer();    
                            mTimerTask = new TimerTask() {    
                                @Override    
                                public void run() {     
                                    if(isChanging==true) {   
                                        return;    
                                    }  
                                    seekbar.setProgress(player.getCurrentPosition());  
                                }    
                            };   
                            mTimer.schedule(mTimerTask, 0, 10);   
                            iffirst=true;  
                        }  
                        player.start();// 开始  
                        ifplay = true;  
                    } else if (ifplay) {  
                        play_pause.setText("继续");  
                        player.pause();  
                        ifplay = false;  
                    }  
                    break;  
                case R.id.reset:  
                    if (ifplay) {  
                        player.seekTo(0);  
                    } else {  
                        player.reset();  
                        try {  
                            player.setDataSource(file.getAbsolutePath());  
                            player.prepare();// 准备  
                            player.start();// 开始  
                        } catch (IllegalArgumentException e) {  
                            e.printStackTrace();  
                        } catch (IllegalStateException e) {  
                            e.printStackTrace();  
                        } catch (IOException e) {  
                            e.printStackTrace();  
                        }  
                    }  
                    break;  
                }  
            }  
        }  
    }  
    //进度条处理  
    class MySeekbar implements OnSeekBarChangeListener {  
        public void onProgressChanged(SeekBar seekBar, int progress,  
                boolean fromUser) {  
        }  
  
        public void onStartTrackingTouch(SeekBar seekBar) {  
            isChanging=true;    
        }  
  
        public void onStopTrackingTouch(SeekBar seekBar) {  
            player.seekTo(seekbar.getProgress());  
            isChanging=false;    
        }  
  
    }  
    //来电处理  
    protected void onDestroy() {  
        if(player != null){  
            if(player.isPlaying()){  
                player.stop();  
            }  
            player.release();  
        }  
        super.onDestroy();  
    }  
  
    protected void onPause() {  
        if(player != null){  
            if(player.isPlaying()){  
                player.pause();  
            }  
        }  
        super.onPause();  
    }  
  
    protected void onResume() {  
        if(player != null){  
            if(!player.isPlaying()){  
                player.start();  
            }  
        }  
        super.onResume();  
    }  
  
} 





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值