Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

In order to receive the only short beep sound on loudspeaker I want to send single bit to the loudspeaker directly. Similarly to the LED blink. Is there any possibility to do short beep without any kind of Media Players?

like image 281
andreikashin Avatar asked Apr 08 '15 07:04

andreikashin


3 Answers

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.

like image 171
Josh Avatar answered Nov 20 '22 06:11

Josh


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())
}
}
like image 27
Kakashi Avatar answered Nov 20 '22 07:11

Kakashi


For Kotlin:

ToneGenerator(AudioManager.STREAM_MUSIC, 100).startTone(ToneGenerator.TONE_PROP_BEEP, 200)
like image 9
Ghayas Avatar answered Nov 20 '22 06:11

Ghayas