Android学习之工具类二:播放声音工具类

​
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

/**
 * 播放声音工具类
 *
 * @author linzhiyong
 * @time 2017-01-16 10:11:16
 * @email wflinzhiyong@163.com
 * @desc
 */
public class SoundPlayer {

    private Context context;
    private SoundPool soundPool;
    private int soundID;

    public SoundPlayer(Context context) {
        this.context = context;
        this.soundPool= new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
    }

    /**
     * 加载声音资源
     *
     * @param resId
     * @return soundID
     */
    public int loadRes(int resId) {
        return this.soundPool.load(this.context, resId, 1);
    }

    /**
     * 播放声音
     *
     * @param soundID
     * @param priority
     * @param isLoop
     */
    public void play(int soundID, int priority, boolean isLoop) {
        this.soundPool.play(soundID, 1, 1, priority, isLoop ? -1 : 0, 1);
    }

    /**
     * 停止
     *
     * @param soundID
     */
    public void stop(int soundID) {
        this.soundPool.stop(soundID);
        this.soundPool.release();
    }

    /**
     * 播放声音
     *
     * @param resId
     * @param isLoop
     */
    public void play(int resId, final boolean isLoop) {
        this.soundID = loadRes(resId);
        this.soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                play(soundID, 0, isLoop);
            }
        });
    }

    /**
     * 停止
     */
    public void stop() {
        stop(this.soundID);
    }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值