soundpool

package com.kerry.demo;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class Demo1Activity extends Activity  implements OnClickListener{

Button buttons [] = new Button[6] ;

SoundPool soundPool;

int streamId;

float  volume ;

// Map hashMap = new HashMap<integer, integer>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initSoundPool();
       
        buttons[0] = (Button) this.findViewById(R.id.button1);
        buttons[1] = (Button) this.findViewById(R.id.button2);
        buttons[2] = (Button) this.findViewById(R.id.button3);
        buttons[3] = (Button) this.findViewById(R.id.button4);
        buttons[4] = (Button) this.findViewById(R.id.button5);
        buttons[5] = (Button) this.findViewById(R.id.button6);
       
        for(Button bt :buttons){
        bt.setOnClickListener(this);
        }
    }

@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:

playSound(1);
Toast.makeText(this,"button1",0).show();
;break;
case R.id.button2:

playSound(2);
Toast.makeText(this,"button2",0).show();
;break;
case R.id.button3:
Toast.makeText(this,"button3",0).show();
pauseSound();
;break;
case R.id.button4:
stopSound();
;break;
case R.id.button5:
playSound(5);
;break;
case R.id.button6:;break;
}
}

public void initSoundPool(){
soundPool = new SoundPool(1,  //同事播放音效的数量
AudioManager.STREAM_MUSIC, //设置音频类型
0); //为以后留得参数  展示设置为0 即可
streamId = soundPool.load(this,R.raw.noitem,1);

AudioManager  audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
int streamMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
int streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

volume = streamVolume/streamMaxVolume;
}

public void playSound(int  mumber){
soundPool.play(
streamId, //声音资源文件
volume,  //左声道
volume,  //右声道
1,    // 优先级  0 为最低
mumber,    //播放次数
1); //0.5~2.0  播放速度
}

public void stopSound(){
soundPool.stop(streamId);
}

public void pauseSound(){
soundPool.pause(streamId);
}
}












你可能感兴趣的:(SoundPool)