1 package com.baorant.soundpooltest; 2 3 import java.util.HashMap; 4 5 import android.app.Activity; 6 import android.media.AudioManager; 7 import android.media.SoundPool; 8 import android.os.Bundle; 9 import android.view.View; 10 import android.view.View.OnClickListener; 11 import android.widget.Button; 12 13 public class MainActivity extends Activity implements OnClickListener { 14 Button bomb, shot, arrow; 15 SoundPool soundPool; 16 HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>(); 17 18 @Override 19 protected void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.activity_main); 22 bomb = (Button) findViewById(R.id.bomb); 23 shot = (Button) findViewById(R.id.shot); 24 arrow = (Button) findViewById(R.id.arrow); 25 /** 26 * 27 * soundPool对象的构造和sdk版本有关 28 * if(Build.VERSION.SDK_INT>=21){ 29 * SoundPool.Builder builder = new SoundPool.Builder(); 30 * builder.setMaxStreams(2);//传入音频数量 //AudioAttributes是一个封装音频各种属性的方法 31 * AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder(); 32 * attrBuilder.setLegacyStreamType(AudioManager 33 * .STREAM_MUSIC);//设置音频流的合适的属性 34 * builder.setAudioAttributes(attrBuilder.build());//加载一个AudioAttributes 35 * mPool = builder.build(); }else{ mPool = new 36 * SoundPool(2,AudioManager.STREAM_MUSIC,0); } 37 */ 38 soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0); 39 soundMap.put(1, soundPool.load(this, R.raw.bomb, 1)); 40 soundMap.put(2, soundPool.load(this, R.raw.shot, 1)); 41 soundMap.put(3, soundPool.load(this, R.raw.arrow, 1)); 42 bomb.setOnClickListener(this); 43 shot.setOnClickListener(this); 44 arrow.setOnClickListener(this); 45 } 46 47 @Override 48 public void onClick(View v) { 49 switch (v.getId()) { 50 case R.id.bomb: 51 soundPool.play(soundMap.get(1), 1, 1, 0, 0, 1); 52 case R.id.shot: 53 soundPool.play(soundMap.get(2), 1, 1, 0, 0, 1); 54 case R.id.arrow: 55 soundPool.play(soundMap.get(3), 1, 1, 0, 0, 1); 56 } 57 58 } 59 60 }
使用soundpool播放声音的步骤如下:
1、使用soundpool.builder的构造器创建sound.builder对象
2、调用soundpool的构造器创建soundpool对象,构造器方法和sdk版本有关,具体参照上面代码内容
3、调用soundpool对象的load()方法加载声音。最好用haspmap来管理加载的声音
4、调用soundpool的play()方法来播放声音