Android SoundPool语音播报工具类

作者: 夕hl月 | 来源:发表于2019-12-16 19:15 被阅读0次

项目中需要用到语音提示,且都是比较简短的语音提示,刚开始的时候用的是MediaPlayer进行语音播放,但是查阅资料发现MediaPlayer主要是用来进行长音频播放,且资源消耗较高,后发现SoundPool进行语音播放时资源消耗更少,且响应速度更快,就写了一个简单的SoundPool工具类,主要是用来进行短音频播放,还可以判断当前是否有音频正在播放。
工具类代码如下:

/**
 * 简短音频播放工具类
 */
public class SoundPoolUtil {
    private volatile static SoundPoolUtil client;
    private SoundPool mSoundPool;
    private AudioManager mAudioManager;
    /*允许同时播放的音频数(为1时会立即结束上一个音频播放当前的音频)*/
    private static final int MAX_STREAMS = 1;
    // Stream type.
    private static final int streamType = AudioManager.STREAM_MUSIC;
    private int mSoundId;
    private int mResId;
    private Context mainContext;

    public static SoundPoolUtil getInstance(Context context) {
        if (client == null)
            synchronized (SoundPoolUtil.class) {
                if (client == null) {
                    client = new SoundPoolUtil(context);
                }
            }
        return client;
    }

    private SoundPoolUtil(Context context) {
        this.mainContext = context;
        mAudioManager = (AudioManager) this.mainContext.getSystemService(Context.AUDIO_SERVICE);
        ((Activity) this.mainContext).setVolumeControlStream(streamType);
        this.mSoundPool = new SoundPool(MAX_STREAMS, streamType, 0);
    }


    /**
     * 播放音频
     * @param resId 本地音频资源
     */
    public void playSoundWithRedId(int resId) {
        this.mResId = resId;
        this.mSoundId = this.mSoundPool.load(this.mainContext, this.mResId, 1);
        this.mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                playSound();
            }
        });

    }
    
    /**
     * 播放音频,但是当前有音频这正播放中时不响应该次音频播放
     * @param resId 本地音频资源
     */
    public synchronized void playSoundUnfinished(int resId) {
        if ( isFmActive()) return;
        this.mResId = resId;
        this.mSoundId = this.mSoundPool.load(this.mainContext, this.mResId, 1);
        mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                playSound();
            }
        });
    }

    /**
     * 播放音频文件
     */
    private void playSound() {
        mSoundPool.play(this.mSoundId, 1.0f, 1.0f, 0, 0, 1f);
    }

    /**
     * 判断当前设备是否正在播放音频
     */
    private boolean isFmActive() {
        if (mAudioManager == null) {
            return false;
        }
        return mAudioManager.isMusicActive();
    }
}

相关文章

网友评论

    本文标题:Android SoundPool语音播报工具类

    本文链接:https://www.haomeiwen.com/subject/ohbdnctx.html