您的位置:首页 > 其它

SoundPool的使用案例

2016-09-24 18:58 225 查看
相比于MediaPlayer, SoundPool的优点有:

1.  所需的资源量较小,反应的延迟也更小

2.  支持多个音频同时播放

3.  可自行设置音频的品质,播放比率等参数

SoundPool适用于播放短而密集的音频

SoundPool主要有load()方法和play方法:

int play(int soundId, float leftVolume, float rightVolume, int priority, int loop, float rate)  : loop: 0为不循环,-1为循环,0.5<= rate <=2.0 

对于音效池SoundPool,一般使用HashMap去管理多个音频

使用案例代码和解释如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn1,btn2;
SoundPool soundPool;
HashMap<Integer,Integer> soundMap = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
//  创建audio属性对象
AudioAttributes attrs = new AudioAttributes.Builder()
//  设置音效使用的场景
.setUsage(AudioAttributes.USAGE_GAME)
//  设置音效的类型
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
//  创建audio
.build();
//  使用SoundPool.Builder创建 SoundPoll对象 并设置属性
soundPool = new SoundPool.Builder()
//  设置音效池属性
.setAudioAttributes(attrs)
//  设置最多可容纳10个音效音频
.setMaxStreams(10)
//  创建音效池
.build();
//  使用HashMap去管理音效池的音频
//  1是priority值,目前没有用
soundMap.put(1,soundPool.load(this,R.raw.a,1));
soundMap.put(2,soundPool.load(this,R.raw.zhenfu,1));
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btn1:
//  播放音频
soundPool.play(soundMap.get(1),1,1,1,0,1);
break;
case R.id.btn2:
soundPool.play(soundMap.get(2),1,1,1,0,1);
break;
}
}
}


布局文件略
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SoundPool