How to play a short beep to Android Phone's loudspeaker programmatically

I recommend you use the ToneGenerator class. It requires no audio files, no media player, and you can customize the beep's volume, duration (in milliseconds) and Tone type. I like this one:

ToneGenerator toneGen1 = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);             
toneGen1.startTone(ToneGenerator.TONE_CDMA_PIP,150);  

You can see into the ToneGenerator object (CMD + click over ToneGenerator. , in Mac), and choose another beep type besides TONE_CDMA_PIP, 150 is the duration in milliseconds, and 100 the volume.


just adding josh's answer. you need to release ToneGenerator using Handler. especially if you got error java.lang.RuntimeException: Init failed at android.media.ToneGenerator.native_setup(Native Method) like i did.

the complete code :

import android.media.AudioManager
import android.media.ToneGenerator
import android.os.Handler
import android.os.Looper

class BeepHelper
{
val toneG = ToneGenerator(AudioManager.STREAM_ALARM, 100)

fun beep(duration: Int)
{
    toneG.startTone(ToneGenerator.TONE_DTMF_S, duration)
    val handler = Handler(Looper.getMainLooper())
    handler.postDelayed({
        toneG.release()
    }, (duration + 50).toLong())
}
}

Tags:

Android