首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >android里面播放声音的方法---执行某项操作发出滴的一声

android里面播放声音的方法---执行某项操作发出滴的一声

作者头像
wust小吴
发布2019-07-08 18:30:07
2.4K0
发布2019-07-08 18:30:07
举报
文章被收录于专栏:风吹杨柳风吹杨柳
/****************提示声音 震动  发送成功之后显示**********/
private MediaPlayer mediaPlayer;
private boolean playBeep;
private static final float BEEP_VOLUME = 0.10f;
private boolean vibrate;
private void initBeepSound() {
if (playBeep && mediaPlayer == null) {
// The volume on STREAM_SYSTEM is not adjustable, and users found it
// too loud,
// so we now play on the music stream.
((Activity) context).setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(beepListener);


AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(),file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException e) {
mediaPlayer = null;
}
}
}

private final OnCompletionListener beepListener = new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(0);
}
};

private static final long VIBRATE_DURATION = 200L;


private void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}



private void initVoice() {
// TODO Auto-generated method stub
playBeep = true;
AudioManager audioService = (AudioManager)context.getSystemService(context.AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
playBeep = false;
}
initBeepSound();
vibrate = true;
}

/*************************************************/

/***************播放声音的另外一种方法*****************/
     private SoundPool soundPool;
     private int music;
     /**哪里要调用就执行这行代码**/
     public void play_voice() {
         soundPool.play(music, 1, 1, 0, 0, 1);
     }
     /**播放声音初始化*/
     public void initVoice2(){
         soundPool= new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//第一个参数为同时播放数据流的最大个数,第二数据流类型,第三为声音质量
         music = soundPool.load(context, R.raw.beep, 1); //把你的声音素材放到res/raw里,第2个参数即为资源文件,第3个为音乐的优先级
     }
/*********************************************/ 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年10月23日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档