手机播放声音和震动

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

首先,播放声音:

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" />



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值