soundPool和audiofocus

audiofocus试验:
使用soundPool来写一个播放音频的porject.
资源初始化:

setContentView(R.layout.activity_main);
        Button bt1 = (Button)findViewById(R.id.bt1);
        Button bt2 = (Button)findViewById(R.id.bt2);
        final SoundPool sp = new SoundPool(1, AudioManager.STREAM_RING, 5);
        final HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(1, sp.load(MainActivity.this, R.raw.maid,1));
        map.put(2,sp.load(MainActivity.this, R.raw.kali,1) );
        final AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

按键响应:


bt1.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    int result = am.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    if(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
        sp.play((Integer) map.get(1), 1, 1, 1, 2, 1);
    }
    }
});
bt2.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    int result = am.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    if(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
        sp.play((Integer) map.get(2), 1, 1, 1, 2, 1);
    }
    }
});

onAudioFocusChangeListener:

final OnAudioFocusChangeListener onAudioFocusChangeListener = new OnAudioFocusChangeListener(){

            @Override
            public void onAudioFocusChange(int focusChange) {
                // TODO Auto-generated method stub
                if(focusChange == AudioManager.AUDIOFOCUS_LOSS){
                }else if(focusChange == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
                }else if(focusChange == AudioManager.AUDIOFOCUS_REQUEST_FAILED){
                }else if(focusChange == AudioManager.AUDIOFOCUS_GAIN){
                }else if(focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT){
                }else{
                }
            }

        };

这个不是完美的验证AudioFocus的样例,因为soudPool构造函数本身就规定了最大音频流的数量
public soundPool(int maxStreams,int streamType,int srcQuality)
所以两个按键轮流响应并不构成对AudioFocus的争夺,只要将最大流数量设置为1,当另一个按键响应的时候另一个音频就是停止了,在这就不考虑这个了。
其二,发现当音频较大几M的时候,soundPool因为要先缓存,程序初运行点击按键会提示需要等待初始化结束,并且audioFocus失去后不会马上静音,而会多播放1s或者2s。
以上是soundPool的问题,至于audioFocus则在于
AudioManager的使用,发起requestAudioFocus的请求,及在AudioFocus发生变化时在onAudioFocusChangeListener的响应处理。基本按api使用即可。
使用AudioFocus的核心是遵从AudioFocus的使用规则,遵循开放软件的标准,因为AudioFocus是一个竞争资源,如果有一个坏家伙不按规则工作就会出现功能失效进而影响其他应用的使用,这个问题在一些app上偶尔出现。
举个例子,在办事窗口前面排队,前面的家伙已经办完事了还不走站在窗口继续喝办事员对话,而你也要和办事员对话,两个人都叽里呱啦,办事员会疯掉。用户就是那个办事员~

你可能感兴趣的:(android,SoundPool,audiofocus)