How do I make my pc speaker beep

I usually use the little utility beep installed on many systems. This command will try different approaches to create a system sound.

There are 3 ways of creating a sound from the beep manpage:

  1. The traditional method of producing a beep in a shell script is to write an ASCII BEL (\007) character to standard output, by means of a shell command such as

    echo -ne '\007'
    

    This only works if the calling shell's standard output is currently directed to a terminal device of some sort; if not, the beep will produce no sound and might even cause unwanted corruption in whatever file the output is directed to.

  2. There are other ways to cause a beeping noise. A slightly more reliable method is to open /dev/tty and send your BEL character there. This is robust against I/O redirection, but still fails in the case where the shell script wishing to generate a beep does not have a controlling terminal, for example because it is run from an X window manager.

  3. A third approach is to connect to your X display and send it a bell command. This does not depend on a Unix terminal device, but does (of course) require an X display.

beep will simply try these 3 methods.


NOTE: This solution emits beeps from the speakers, not the motherboard.

ALSA comes with speaker-test, a command-line speaker test tone generator, which can be used to generate a beep:

$ speaker-test -t sine -f 1000 -l 1

See this arch linux forum thread.

However, the beep duration will be arbitrary, but can be controlled as follows:

$ ( speaker-test -t sine -f 1000 )& pid=$! ; sleep 0.1s ; kill -9 $pid

We can take it one step further and output a beep with this function:

_alarm() {
  ( \speaker-test --frequency $1 --test sine )&
  pid=$!
  \sleep 0.${2}s
  \kill -9 $pid
}

which is called with frequency and duration arguments:

$ _alarm 400 200

With this in mind, it is possible to create simple music with speaker-test. See this shell script.


Simply echoing \a or \07 works for me.

$ echo -e "\a"

This will probably require the pcspkr kernel module to be loaded. I've only tested this on RHEL, so YMMV.

UPDATE

As Warren pointed out in the comments, this may not work when logged in remotely via SSH. A quick workaround would be to redirect the output to any of the TTY devices (ideally one that is unused). E.g.:

$ echo -en "\a" > /dev/tty5

Tags:

Command Line