android多媒体——4步学会SoundPool

之前学习过了MediaPlayer用于播放手机音乐,但是在手机中很多的提示音并不是使用MediaPlayer来播放的比如短信铃声,通知铃声,android中使用SoundPool来播放小的音频文件;

下面一起学习SoundPool的使用
【1】先搭界面设置一个按钮用于播放开始

【2】得到SoundPool

查看API,得知要得到SoundPool根据版本不同有两种方式
21版本以前使用
SoundPool pool =new SoundPool(int maxStreams, int streamType, int srcQuality)

21版本之后:使用Builder来生成

【3】调用load方法加载音频
android多媒体——4步学会SoundPool_第1张图片
【4】调用play方法
public final int play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)

参数介绍
Parameters
soundID a soundID returned by the load() function
leftVolume left volume value (range = 0.0 to 1.0)左声道
rightVolume right volume value (range = 0.0 to 1.0)右声道
priority stream priority (0 = lowest priority)优先级
loop loop mode (0 = no loop, -1 = loop forever)循环与否
rate playback rate (1.0 = normal playback, range 0.5 to 2.0)播放返回的速度

注意事项

如果你的没有声音,那是因为加载音频需要时间,不要把load和play放在一起
也不要使线程休眠,以免阻碍主线程

下面是源码

public class MainActivity extends Activity {
    private Button mButton;
    private SoundPool pool = null;
    private int id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button) findViewById(R.id.button_sound);
        //必须放在外面因为加载音频需要时间不然会没有声音
        id= initSound();
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playSound();
            }
        });

    }


    private void playSound() {


        //public final int play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)
// Parameters
// soundID a soundID returned by the load() function
// leftVolume left volume value (range = 0.0 to 1.0)左声道
// rightVolume right volume value (range = 0.0 to 1.0)右声道
// priority stream priority (0 = lowest priority)优先级
// loop loop mode (0 = no loop, -1 = loop forever)循环与否
// rate playback rate (1.0 = normal playback, range 0.5 to 2.0)播放返回的速度
        pool.play(id, 1, 1, 0, -1, 1);
    }

    public int initSound() {
        if (Build.VERSION.SDK_INT > 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            builder.setMaxStreams(2);
            AudioAttributes.Builder builder1 = new AudioAttributes.Builder();
            builder1.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            builder.setAudioAttributes(builder1.build());
            pool = builder.build();

        } else {
            //21版本以前使用SoundPool(int maxStreams, int streamType, int srcQuality)
            pool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
        }
        return  pool.load(getApplicationContext(), R.raw.outgoing, 1);

    }
}

你可能感兴趣的:(android,多媒体,SoundPool)