How do I access Android's default beep sound?

不羁的心 提交于 2019-12-17 10:21:44

问题


I would like to make a button play a beep sound to indicate it has been pressed. I want to know how to use the default android beep sound (like when you adjust the ringer volume), instead of importing my own mp3 music file or using ToneGenerator?


回答1:


public void playSound(Context context) throws IllegalArgumentException, 
                                              SecurityException, 
                                              IllegalStateException,
                                              IOException {

    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    MediaPlayer mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setDataSource(context, soundUri);
    final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

    if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        // Uncomment the following line if you aim to play it repeatedly
        // mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    }
}

I found another answer:

try {
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
    r.play();
} catch (Exception e) {
    e.printStackTrace();
}

credit goes to https://stackoverflow.com/a/9622040/737925




回答2:


... use the default android beep sound (like when you adjust the ringer volume) ...

On my Cyanogen 7 Nexus One and my old stock T-Mobile Pulse Mini (the latter from memory), as far as I can hear, this is is exactly the default beep sound on volume change:

     final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
     tg.startTone(ToneGenerator.TONE_PROP_BEEP);

You seem to be asking for an alternative to ToneGenerator, but I think it gives you exactly what you want in two lines.

Here are some other likely ToneGenerator sounds I tried that were not a match (the first two might be useful as alternates to the volume beep):

     // Double beeps:     tg.startTone(ToneGenerator.TONE_PROP_ACK);
     // Double beeps:     tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
     // Sounds all wrong: tg.startTone(ToneGenerator.TONE_CDMA_KEYPAD_VOLUME_KEY_LITE);



回答3:


the easy way is to use instance of ToneGenerator classe:

    //declaration
    ToneGenerator toneG;
    //using any where`
    if(val>=taux_max)
    {
        taux_text.setTextColor(warnning_col);
        toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200); //200 is duration in ms
    }


来源:https://stackoverflow.com/questions/6462105/how-do-i-access-androids-default-beep-sound

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!