Android 使用 ToneGenerator 编写按键发声功能
2010-11-05 00:56:27 来源:WEB开发网Java代码
private ToneGenerator mToneGenerator;
private Object mToneGeneratorLock = new Object();//监视器对象锁
private boolean mDTMFToneEnabled; //按键操作音
private static final int TONE_LENGTH_MS = 150;//延迟时间
void playTone(int tone) {
// TODO 播放按键声音
if (!mDTMFToneEnabled) {
return;
}
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int ringerMode = audioManager.getRingerMode();
if ((ringerMode == AudioManager.RINGER_MODE_SILENT)
|| (ringerMode == AudioManager.RINGER_MODE_VIBRATE)) {//静音或震动时不发出按键声音
return;
}
synchronized(mToneGeneratorLock) {
if (mToneGenerator == null) {
Log.w(TAG, "playTone: mToneGenerator == null, tone: "+tone);
return;
}
mToneGenerator.startTone(tone, TONE_LENGTH_MS);//发声
}
}
protected void onResume(){
super.onResume();
mDTMFToneEnabled = Settings.System.getInt(getContentResolver(),
Settings.System.DTMF_TONE_WHEN_DIALING, 1) == 1;//获取系统参数“按键操作音”是否开启
synchronized(mToneGeneratorLock) {
if (mToneGenerator == null) {
try {
mToneGenerator = new ToneGenerator(AudioManager.STREAM_MUSIC, 80);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
} catch (RuntimeException e) {
Log.w(TAG, "Exception caught while creating local tone generator: " + e);
mToneGenerator = null;
}
}
}
}
Tags:Android 使用 ToneGenerator
编辑录入:coldstar [复制链接] [打 印]更多精彩
赞助商链接