SoundUtils.java
2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.huaheng.mmsrf.util;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;
import com.huaheng.mmsrf.R;
/**
 * Created by Administrator on 2017-7-27.
 */
public class SoundUtils {
    private static SoundUtils mySoundUtils;
    private static Vibrator vibrator;
    private Context context;
    private SoundPool soundPool;
    public static SoundUtils getInstance(Context context) {
        if (mySoundUtils == null) {
            mySoundUtils = new SoundUtils(context);
        }
        return mySoundUtils;
    }
    private SoundUtils(Context context) {
        this.context = context;
        initSoundPool();
    }
    private void initSoundPool() {
        if (soundPool != null) return;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            SoundPool.Builder builder = new SoundPool.Builder();
            builder.setMaxStreams(5);
            //AudioAttributes是一个封装音频各种属性的方法
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);//设置音频流的合适的属性
            builder.setAudioAttributes(attrBuilder.build());//加载一个AudioAttributes
            soundPool = builder.build();
        } else {
            soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 5);
        }
        soundPool.load(context, R.raw.finish, 1);
        soundPool.load(context, R.raw.open, 1);
        soundPool.load(context, R.raw.beep, 1);
        soundPool.load(context, R.raw.error, 1);
        soundPool.load(context, R.raw.changecode, 1);
    }
    public void finishSound() {
        if (soundPool != null) soundPool.play(1, 0.3f, 0.3f, 100, 0, 1);
    }
    public void openSound() {
        if (soundPool != null) soundPool.play(2, 0.3f, 0.3f, 100, 0, 1);
    }
    public void dingSound() {
        if (soundPool != null) soundPool.play(3, 0.3f, 0.3f, 100, 0, 1);
    }
    public void errorSound() {
        if (soundPool != null) soundPool.play(4, 0.3f, 0.3f, 100, 0, 1);
    }
    public void changeSound() {
        if (soundPool != null) soundPool.play(5, 0.3f, 0.3f, 100, 0 ,1);
    }
}