手机播放声音和震动

来源:互联网 发布:洛阳青峰网络黄伟 编辑:程序博客网 时间:2024/04/28 07:09

在游戏开发时,加上声音和震动会让游戏看起来非常上等。

首先,播放声音:

public class SoundManager {    private static SoundManager soundManager;  private Context context;  private SoundPool soundPool;  private HashMap<Integer, Integer> soundPoolMap;  public static final int SHOOT=1;    private SoundManager(Context context){    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);    soundPoolMap = new HashMap<Integer, Integer>();    soundPoolMap.put(SHOOT, soundPool.load(context, R.raw.bulletsound, 1));    this.context = context;  }     public static SoundManager newInstance(Context context){    if(soundManager == null){      soundManager = new SoundManager(context);          }    return soundManager;  }    public void playSound(int type){    AudioManager mgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);    float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);        float volume = streamVolumeCurrent / streamVolumeMax;    /* 使用正确音量播放声音 */    soundPool.play(soundPoolMap.get(type), volume, volume, 1, 0, 1f);       }}
声音文件加载只需要加在一起,所以我把SoundManager设计为单例的。


震动:

Vibrator vibrator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);vibrator.vibrate(new long[] {100, 10, 10, 100}, -1);  //-1短震动

注意需要在AndroidManifest.xml文件中加入下面这行:

<uses-permission android:name="android.permission.VIBRATE" />



原创粉丝点击