SoundPool没有声音

看代码,使用SoundPool加载tab_click_sound.mp4播放没有声音

SoundPool soundPool = new SoundPool.Builder().build();
int soundID = soundPool.load(context, R.raw.tab_click_sound, 1);
soundPool.play(
        soundID,
        1,      //左耳道音量【0~1】
        1,      //右耳道音量【0~1】
        0,         //播放优先级【0表示最低优先级】
        0,         //循环模式【0表示循环一次,-1表示一直循环,其他表示数字+1表示当前数字对应的循环次数】
        1          //播放速度【1是正常,范围从0~2】
);

原因:SoundPool用的其他线程加载资源,这个时候播放资源还没有加载完全,所以没有声音,我们需要提前加载

比如1:放到onCreate,再比如Application中提前加载好,使用的时候只需要soundPool.play就可以了

上代码,懒得写的直接复制用吧

下面是我正在用的,在Application中initSound初始化资源,全app都可以用playSound播放

public class SoundUtil {
    private static SoundPool soundPool = null;
    private static int soundID;

    /**
     * 需要提前初始化,初始化需要一点时间,这个时候play是没有声音的
     * @param context
     */
    public static void initSound(Context context) {
        if (soundPool == null) {
            soundPool = new SoundPool.Builder().build();
            soundID = soundPool.load(context, R.raw.tab_click_sound, 1);

        }
    }

    public static void playSound() {
        if (soundPool != null) {
            soundPool.play(
                    soundID,
                    1,        //左耳道音量【0~1】
                    1,       //右耳道音量【0~1】
                    0,           //播放优先级【0表示最低优先级】
                    0,             //循环模式【0循环一次,-1一直循环,其他表示数字+1表示当前数字对应的循环次数】
                    1               //播放速度【1正常,范围0~2】
            );
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容