107

I'd like to use a beep sound in a shell script. Unfortunately none of the methods I found via Google work for me.

I tried

echo -e '\a'

echo -ne '\007'

and the command beep after I installed it via apt.

What could be the reason?

Seth
  • 58,122
NES
  • 33,195
  • See this bug report: https://bugs.launchpad.net/ubuntu/+source/unity/+bug/769314 – Flimm Dec 02 '14 at 23:58
  • http://superuser.com/questions/47564/remotely-make-the-computer-beep-on-built-in-speaker || http://unix.stackexchange.com/questions/1974/how-do-i-make-my-pc-speaker-beep || http://stackoverflow.com/questions/10313939/how-to-emit-a-beep-on-my-computer-while-running-a-script-on-a-remote-machine – Ciro Santilli OurBigBook.com Sep 30 '15 at 14:52
  • For a Nice PulseAudio Bell Sound in Xubuntu

    See: https://askubuntu.com/questions/1310345/how-to-fix-gnome-terminal-bell-in-xubuntu-20-04

    – Steve Holmes Jan 23 '21 at 11:37
  • If your terminal is terminator, see my Q&A here for the answer: https://askubuntu.com/questions/1253799/terminator-terminal-wont-play-bell-sound/1253800#1253800. – Gabriel Staples Apr 28 '21 at 04:18

17 Answers17

119

Not being a fan of the pcspkr beep, I use a beep from one of the system sounds with the installed pulseaudio server's paplay command.

First find a sound you like (you can browse /usr/share/sounds for some available ones for example) and create a reference to it

export BEEP=/usr/share/sounds/ubuntu/ringtones/Harmonics.ogg

Then have it available as a command

alias beep='paplay $BEEP'

Now just run beep whenever you need it. For example, to alert you when a command is finished:

find . | grep treasure ; beep
yuvilio
  • 3,389
  • 2
    Can you get it to play this sound when someone runs echo -e '\a' – Flimm Dec 02 '14 at 23:22
  • You might need some read command in a while loop or some other library that can monitore keystrokes. – yuvilio Dec 11 '14 at 01:12
  • 7
    This is a great solution! Now I can do run-my-long-test-suite.sh; beep and read stackoverflow until the system is ready. – jamesc Mar 30 '15 at 10:17
  • 4
    Nice! I use export BEEP=/usr/share/sounds/ubuntu/stereo/dialog-information.ogg and alias beep='paplay $BEEP --volume=32768' now, that works well for me. (Note that you can override the volume with the beep alias, e.g. beep --volume=15000 plays at volume of -12dB.) – leftaroundabout Dec 06 '15 at 12:57
  • 5
    Playing these ogg files can result in latency orders of magnitude greater than that of the internal PC speaker beep. Not only that the latency seems highly variable. I acknowledge that most people don't care but when you need real time or near real time responsiveness the PC speaker is probably the best option for audible feedback. – H2ONaCl Feb 21 '18 at 19:59
  • This does not answer the question at all – phil294 Mar 24 '18 at 00:06
  • If you like this, you might also like spd-say "Analysis complete" – Jonathan Hartley Oct 28 '21 at 15:45
  • Unfortunately this approach doesn't work if I want to trigger a beep sound in an SSH session (i.e. from a command in a remote server). However, if I could get the echo command to work, then it would be possible: https://serverfault.com/questions/500839/let-the-local-machine-beep-when-some-event-happen-on-remote – Silveri Dec 12 '22 at 10:38
109

First run sudo modprobe pcspkr and then beep should work.

The reason this doesn't is because by default Ubuntu no longer loads the hardware driver that produce beeps.

If this works for you then to enable the loading of pcspkr permanently edit the /etc/modprobe.d/blacklist.conf file (using gksudo gedit perhaps) and comment out line that says blacklist pcspkr so it looks like this:

# ugly and loud noise, getting on everyone's nerves; this should be done by a
# nice pulseaudio bing (Ubuntu: #77010)
# blacklist pcspkr
8128
  • 28,740
  • 4
    If I comment blacklist pcspkr I have to do modprobe -r pcspkr && modprobe pcspkr to get it to work. Also getting beep to work is not the same as getting the audible bell to work and thus http://askubuntu.com/questions/22168/how-do-i-enable-the-terminal-bell should still be open. – daithib8 Jul 28 '11 at 11:37
  • 5
    This doesn't work for me in Ubuntu 14. – Cerin Apr 04 '16 at 23:41
  • This will mostly likely never work on modern laptops, as they don't have a speaker device. Instead see my answer below on how to use paplay. (I wasted a bunch of time chasing down this, only to get silence.) – Elliptical view Apr 22 '20 at 01:08
30

Since this is a very high rated question on google, I'll add the steps I did to re-enable beep in both console and X11:


For the Linux Console (CTRL+ALT+F1...F6):

Why it does not work by default

As already answered, the pcspkr kernel driver for the PC Speaker is blacklisted in Ubuntu.

Temporarily enable until reboot:

sudo modprobe pcspkr

Automatically enable on boot:

sudo nano /etc/modprobe.d/blacklist.conf

(delete or comment pcspkr line by prepending it with #)


For X11 terminals (such as the default gnome-terminal)

Why it does not work by default

Under X, like when using Unity, KDE, Gnome Shell, the beep events are captured by PulseAudio thanks to module-x11-bell, which is loaded by default at /usr/bin/start-pulseaudio-x11. And the sound sample PulseAudio plays on beep, bell.ogg, is blank by default. Additionally, the bell volume may be muted.

To temporarily enable for current session,

xset b 100  # perhaps not needed, on my system it was 40 by default
pactl upload-sample /usr/share/sounds/ubuntu/stereo/bell.ogg bell.ogg

There are other suitable samples you can try at /usr/share/sounds, for example check the ones at /usr/share/sounds/gnome/default/alerts/

Note that the beep program is not really necessary. But if installed, it uses the PC Speaker. It was the only way I could find to enable the buzzer under X:

sudo apt-get install beep

To automatically enable on boot, just add the above lines in your ~/.profile, or system-wide at /etc/profile


To test it:

printf '\a'

Beep!

beep

Buzz!

muru
  • 197,895
  • 55
  • 485
  • 740
MestreLion
  • 20,086
  • To automatically enable a pc speaker beep on boot you have to actually comment said line in /etc/modprobe.d/blacklist.conf not uncomment it (you want to disable blacklisting, not the other way around). – z33k Sep 16 '16 at 11:18
  • 1
    both solutions work on Ubuntu 16.04 Note: pcspkr and bell.ogg are independent approaches. beep tries to beep using various approaches e.g., ioctl(console_fd, KIOCSOUND, period) use pcspkr (the sound is coming from PC speaker on the motherboard) while printf '\a' -based method may work without it using only bell.ogg (the sound is from ordinary speakers). The second method might not work until pulseaudio service is started and/or xset b on is run – jfs Oct 13 '16 at 00:43
  • The pactl upload-sample ... was golden for me. What's the way to permanently configure the sample loading again? – ulidtko Nov 29 '16 at 22:15
  • @ulidtko: Just add those lines lines in your ~/.profile, or system-wide at /etc/profile – MestreLion Feb 06 '17 at 15:40
  • @MestreLion wrong. load-sample bell.ogg /usr/share/sounds/ubuntu/stereo/bell.ogg in /etc/pulseaudio/default.pa. – ulidtko Feb 07 '17 at 10:19
25

I've encountered this problem before. From what I remember, the problem is that the terminal bell tries to ring an internal computer speaker (as in an old-school desktop) but laptops and some newer computers are missing such a thing.

The only solution I found at the time was to

sudo apt-get install sox

and

play -n synth <duration in seconds> sine <freq in Hz> vol <volume (0-1)>

e.g.

 play -n synth 0.1 sine 880 vol 0.5
M.A.K. Ripon
  • 3,139
YodaDaCoda
  • 1,555
23

To fix this problem persistently:

  • Run gconf-editor and if the desktop | gnome | peripherals | keyboard | bell_mode setting is present then change it from off to on
  • Run dconf-editor and if the org | gnome | settings-daemon | peripherals | keyboard | bell-mode setting is present then change it from off to on
  • Add pactl upload-sample /usr/share/sounds/gnome/default/alerts/glass.ogg bell.ogg to the file ~/.xprofile (you need gnome-control-center-data for glass.ogg)
  • Add [ "$DISPLAY" ] && xset b 100 to the file ~/.bashrc

The simplest way to activate this solution is to reboot.

Further, to implement this solution immediately for a terminal window that is already open, run the pactl command and run the xset command in the terminal window in question.

jdthood
  • 12,467
9

"Beep can only work if your PC has a traditional old style "speaker", and probably most if not all laptops and small devices don't have one.

However what they often have instead is a sound chip and one or more speaker(s) that can be used to make any sound you want.

So the outdated advise to install the beep command and/or the kernel module pcspkr will silently never work when you don't have the old style speaker hardware.

INSTEAD: Try playing a sound like this when you want a beep:

paplay /usr/share/sounds/sound-icons/capital

Note this uses the paplay (Pulse Audio Play) command which mixes better with other user level (user app) sounds on your system, and not the older aplay (ALSA Play) command which generally can only play one sound at the same time. But note however, that PulseAudio calls ALSA to actually play the sound.

My previous suggestion to use play might still work, but running SoX of which play is from, is overkill.


Works for me when all else failed. Thanks to: tredegar & hk_centos and others.

4

I finally found a solution, which doesn't require alsamixer to have a PC Beep option. I think I remember all my changes:

uncomment the following in /etc/pulse/default.pa:

load-sample-lazy x11-bell /usr/share/sounds/ubuntu/stereo/bell.ogg
load-module module-x11-bell sample=bell-windowing-system

per this bug, run pactl upload-sample /usr/share/sounds/ubuntu/stereo/bell.ogg bell.ogg

David Foerster
  • 36,264
  • 56
  • 94
  • 147
JoBu1324
  • 639
  • Tried this, pactl gave me Connection failure: Connection refused pa_context_connect() failed: Connection refused. – YodaDaCoda Dec 11 '12 at 23:33
  • Maybe this thread will help - if you've ever run pulseaudio as root. – JoBu1324 Dec 11 '12 at 23:49
  • I'm having a different problem, actually. Pulseaudio throws Failed to open module "module-esound-protocol-unix": file not found. Probably not worth discussing here since I'm running 13.04, though I would love to be able to verify your solution. – YodaDaCoda Dec 12 '12 at 00:05
  • Nice, just slightly different lines for 15.04. – VRR Sep 12 '15 at 11:09
3

It might be to late BUT, for the guy in the future looking for this:

printf '\x07'
Schalk
  • 251
2

An alternative approach - set your xterm / console to "Visual Bell" so that when it would beep, the window simply inverts its colours for a short time.

I have a bash function called beep to get my attention once a command is finished.

beep ()  { while true; do  echo -en '\a'; sleep 1; done }

And it is used this way

longrun-command ; beep
Criggie
  • 681
2

I added this little function to my .bashrc as a replacement for beep:

beep () {
    if [ "$1" = --list ]
    then
        find /usr/share/sounds -type f -exec basename {} \; | sort -n | tr '\n' ' '; echo
    else
        paplay $(find /usr/share/sounds -type f -iname "${1:-bell}*" | head -1)
    fi
}

It searches for a file in /usr/share/sounds starting with supplied argument or "bell" and plays it. beep --list returns list of files in /usr/share/sounds.

# Examples
beep
beep bark
beep trump
Kris
  • 121
2

As far as I can tell, this is a bug: System beep broken in Karmic despite heroic efforts to fix it.

Flimm
  • 41,766
htorque
  • 64,798
  • 3
    "Not enabled by default" does not mean broken, and no "heroic effort" is needed: just modprobe pcsprk (in console) or pactl upload-sample ... in X11 and the annoying beep is back :) – MestreLion Feb 19 '15 at 11:03
2

If you have actual speakers connected to the computer and you're not getting a beep it's likely because you are using compiz. Compiz is relying on pulseaudio catching the beeps and playing them while metacity bypasses the usual setup and uses libcanberra to play a beep sound. If it works with metacity and not compiz that is your problem, otherwise the answer htorque gave is corrent.

1
paplay /usr/share/sounds/purple/alert.wav
Noel
  • 131
1

Today, June 2020, in Ubuntu 18.04, the whole sudo modprobe pcspkr and commenting out of the blacklist pcspkr part of the /etc/modprobe.d/blacklist.conf file, as described here, doesn't seem to be necessary.

Mine is still blacklisted, yet my bell character sound works just fine!

$cat /etc/modprobe.d/blacklist.conf 
.
.
.
# ugly and loud noise, getting on everyone's nerves; this should be done by a
# nice pulseaudio bing (Ubuntu: #77010)
blacklist pcspkr

Instead, just make sure the Terminal bell sound is turned ON in your gnome-terminal settings:

Right-click on the screen in gnome-terminal --> Preferences --> check the box for "Terminal bell" under the "Sound" section, as shown below:

enter image description here

Now run this, and hear the dull "thud" sound of the bell character sound:

echo -e "\a"

This also works over remote ssh sessions, which is super handy when building on a remote machine, for instance, so that it will play the bell sound when the build is done, to alert you:

time bazel build //...; echo -e "\a"

Also note that pressing Backspace when there's nothing to delete will also play this sound in gnome-terminal.

Related:

  1. `terminator` terminal won't play bell sound
  2. Update: Also see @jvriesem's response to my question in the comments under this question here: How do I enable the terminal bell?. I seem to be answering a slightly different question.
1

Some motherboards don't have a beep speaker. To get around this, I created a Python script that instead uses FFmpeg's aevalsrc filter to generate beep noises.

Note: you will need to install FFmpeg using sudo apt install ffmpeg

#!/usr/bin/env python3
# This program runs FFPlay to generate beeps.

from argparse import ArgumentParser, ArgumentError, Action import re import subprocess

Custom action for note

class NoteToFrequencyAction(Action): _note = re.compile(r"([A-G])(bb|[bx#])?(\d+)") _note_factors = { "C": lambda x: x / (2 ** (9/12)), "D": lambda x: x / (2 ** (7/12)), "E": lambda x: x / (2 ** (5/12)), "F": lambda x: x / (2 ** (4/12)), "G": lambda x: x / (2 ** (2/12)), "A": lambda x: x, "B": lambda x: x * (2 ** (2/12)), } _accidental_factors = { "x" : lambda x: x * (2 ** (2/12)), "#" : lambda x: x * (2 ** (1/12)), None: lambda x: x, "b" : lambda x: x / (2 ** (1/12)), "bb": lambda x: x / (2 ** (2/12)) } def call(self, parser, namespace, values, option_string) -> None: if not (isinstance(values, str)): raise ArgumentError("Should not have multiple values")

    parse = self._note.fullmatch(values);
    parts = parse.groups()

    freq = 440.0
    freq *= 2 ** (int(parts[2]) - 4)
    freq = self._note_factors[parts[0]](freq)
    freq = self._accidental_factors[parts[1]](freq)

    if not type(namespace.__dict__[self.dest]) == list:
        namespace.__dict__[self.dest] = []
    namespace.__dict__[self.dest].append(freq)




parser = ArgumentParser()

freq_group = parser.add_mutually_exclusive_group(required=True) freq_group.add_argument("-f", "--frequency", type=float, action="append", dest="freqs", help="Can be specified more than once, specifies frequencies in Hz of the beeped notes" ) freq_group.add_argument("-n", "--note", action=NoteToFrequencyAction, dest="freqs", help="Can be specified more than once, specifies notes (e.g. A4). You can use b, #, x, bb for accidentals." )

parser.add_argument("-d", "--duration", type=float, default=1, dest="time", help="The duration of the beep in seconds." ) parser.add_argument("-v", "--volume", type=float, default=0.5, help="The volume of the beep, defaults to 0.5" )

args = parser.parse_args() del parser, freq_group

aevalsrc_waves = [f"sgn(sin({repr(f)}2PI*t))" for f in args.freqs] aevalsrc_expr = "+".join(aevalsrc_waves) ffplay_filter = f"aevalsrc=({aevalsrc_expr})/{len(args.freqs)}*{args.volume}:d={args.time}" print("aevalsrc filter:") print(ffplay_filter)

subprocess.run([ "ffplay", "-f", "lavfi", "-i", ffplay_filter, "-autoexit", "-nodisp" ], stderr=subprocess.DEVNULL)

Simply paste into ~/bin/beep and chmod +x beep to make it available. It doesn't quite support the same options, but doing that would make this code a lot longer than it already is.

0

This answer works for me using Ubuntu Server with Cinnamon desktop environment installed. The terminal bell was not working by default.

My solution is similar to the answer by @jdthood: I was able to fix it by toggling /org/gnome/desktop/wm/preferences/audible-bell to true using dconf-editor.

0

Some users experiencing the issue in question will only need to open up the Settings GUI, navigate to 'Sound', and under 'Volume Level' increase 'System Sounds' to a nonzero value ( and double-check that 'System Volume' is also nonzero ).

If anyone wants me to add a screenshot, let me know.

elscan
  • 1