162

I'm trying to get the program to give me a beeping noise. I'm on a windows machine. I've looked at http://docs.python.org/library/winsound.html

But not sure how I can program this with a barcode scanner.

Here is my code for the serial barcode scanner.

ser = serial.Serial()
ser.baudrate = 9600

#for windows
ser.port = 2 #for COM3

ser.open()
ser.write('hello')
ser.close()

UPDATE: Since I'm annoying my co-workers with the beep. Can I get it to come through the audio jack for headphones?

dsolimano
  • 8,870
  • 3
  • 48
  • 63
Marc Brigham
  • 2,114
  • 5
  • 22
  • 27

13 Answers13

234

On Windows, if you want to just make the computer make a beep sound:

import winsound
frequency = 2500  # Set Frequency To 2500 Hertz
duration = 1000  # Set Duration To 1000 ms == 1 second
winsound.Beep(frequency, duration)

The winsound.Beep() can be used wherever you want the beep to occur.

Oddthinking
  • 24,359
  • 19
  • 83
  • 121
CyanRook
  • 8,664
  • 4
  • 21
  • 20
188

The cross-platform way to do this is to print('\a'). This will send the ASCII Bell character to stdout, and will hopefully generate a beep (a for 'alert'). Note that many modern terminal emulators provide the option to ignore bell characters.

Since you're on Windows, you'll be happy to hear that Windows has its own (brace yourself) Beep API, which allows you to send beeps of arbitrary length and pitch. Note that this is a Windows-only solution, so you should probably prefer print('\a') unless you really care about Hertz and milliseconds.

The Beep API is accessed through the winsound module: http://docs.python.org/library/winsound.html

Cyberwiz
  • 11,027
  • 3
  • 20
  • 40
jforberg
  • 6,537
  • 3
  • 29
  • 47
  • 2
    Although he asked specifically for Windows, I think this is the all around better solution, unless the WinSound API will revert to \a for OS independant. There are plenty of audio APIs as well – Setheron Jun 30 '11 at 16:17
  • 2
    Frankly, I would avoid playing PC-speaker beeps altogether in a serious programming effort. If he is indeed on Windows, he should probably try to play the system theme's default "alert" signal instead. With any luck, that signal is accessible through whatever GUI package he's using. – jforberg Jun 30 '11 at 16:25
  • 3
    If you use print in a console app, consider adding end="" to prevent a newline every time you beep. – Tony Jul 28 '14 at 15:13
  • 2
    @jforberg The api for that is [winsound.MessageBeep](https://docs.python.org/2/library/winsound.html#winsound.MessageBeep) which can take MB_ICONASTERISK, MB_ICONEXCLAMATION, MB_ICONHAND, MB_ICONQUESTION, and MB_OK. – Peter Wood Sep 28 '14 at 20:49
  • Also, if you're using `curses`, you can use `curses.beep()`. Haven't tested it to see if it works in the Windows version of `curses` yet. – ArtOfWarfare Feb 21 '15 at 19:48
  • This doesn't work in cygwin. I have a alias set up to do "doThis && cd there && doThat && cd here && doTheOtherThing" but the problem is that doThis, doThat, and doTheOtherThing all take a while, and doThat waits for user input, so I might go off and minimize that window and go do something else, not realizing that it is waiting for me. I thought maybe I could do a quick python script because echo -ne '\007' also does not work. I dont have the ability to use winsound from the accepted answer on my machine either. Does anyone have any suggestions? or is this a new question on superuser? – searchengine27 Mar 16 '15 at 17:06
  • @searchengine27 That's a new question – jforberg Mar 17 '15 at 20:08
  • 3
    If you're using Python 3, don't forget to use parentheses or you'll get a syntax error. Use print('\a') – ZorroDeLaArena Mar 27 '15 at 19:38
  • "If he is indeed on Windows, he should probably try to play the system theme's default "alert" signal instead. With any luck, that signal is accessible through whatever GUI package he's using." FWIW, printing a `\a` does exactly that nowadays (at least on my Win10 system). – Karl Knechtel Oct 18 '18 at 06:26
  • On **MacOS** `\a` briefly dims the terminal window. A kinder, gentler beep. – Bob Stein Mar 07 '19 at 15:35
  • '\a' does NOT play anything for me on windows. – M.Hossein Rahimi Dec 30 '21 at 19:38
  • Trying to do this in python installed in termux on android. It does not play audio but vibrates. Any idea how to make it work? – MsA Nov 25 '22 at 18:07
41

Linux.

$ apt-get install beep

$ python
>>> os.system("beep -f 555 -l 460")

OR

$ beep -f 659 -l 460 -n -f 784 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 880 -l 230 -n -f 659 -l 230 -n -f 587 -l 230 -n -f 659 -l 460 -n -f 988 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 1047-l 230 -n -f 988 -l 230 -n -f 784 -l 230 -n -f 659 -l 230 -n -f 988 -l 230 -n -f 1318 -l 230 -n -f 659 -l 110 -n -f 587 -l 230 -n -f 587 -l 110 -n -f 494 -l 230 -n -f 740 -l 230 -n -f 659 -l 460
  • 14
    Downvoted for two reasons: first, GNU/Linux != Debian and apt-get isn't universal; second, you shouldn't use os.system, use the subprocess module instead. – Ben Feb 04 '15 at 10:42
  • 1
    As a linux user trying to get a simple and cheap beep going for when a long code finishes, this was by and far the easiest solution. I especially loved the little jingle! Note that you may have to call "sudo modprobe pcspkr" and install beep before this option will work, according to https://askubuntu.com/questions/19906/beep-in-shell-script-not-working – John Haberstroh Apr 17 '17 at 03:07
  • 14
    `os.system` is fine, especially with a hardcoded value, not everyone is writing a webserver. – c z Dec 05 '18 at 16:02
  • typo `-f 1047-l`, should be `-f 1047 -l`, space missing –  Jun 26 '20 at 13:18
  • 7
    @Ben Old question, but fwiw it seems pretty harsh to downvote this. The question relates to an area with no cross-platform solution as I understand it. The accepted answer with 140 likes is Windows-specific. And you don't explain why a legitimate module is "bad" practice. – geotheory Jul 14 '20 at 08:43
  • @geotheory this appears to be a typical case where adhesion to an arbitrary subset of specifics is upheld over the net (or big picture) relevance. It's highly likely any programmer who can use Linux, would know how to install packages or could easily figure it out. As for the second premise, it looks like c z might be correct in the same way as to the relevance. – ecv Oct 12 '21 at 14:18
35

There's a Windows answer, and a Debian answer, so here's a Mac one:

This assumes you're just here looking for a quick way to make a customisable alert sound, and not specifically the piezeoelectric beep you get on Windows:

os.system( "say beep" )

Disclaimer: You can replace os.system with a call to the subprocess module if you're worried about someone hacking on your beep code.

See: How to make the hardware beep sound in Mac OS X 10.6

c z
  • 7,726
  • 3
  • 46
  • 59
24

I was searching for the same but for Linux shell.

The topic brought me to an answer, -thanks-

Maybe more pythonic manner :

import os
beep = lambda x: os.system("echo -n '\a';sleep 0.2;" * x)
beep(3)

Notes :

  • the sleep value (here 0.2), depends on the length (seconds) of your default beep sound
  • I choosed to use os.system rather then subprocess.Popen for simplicity (it could be bad)
  • the '-n' for echo is to have no more display
  • the last ';' after sleep is necessary for the resulting text sequence (*x)
  • also tested through ssh on an X term
s4mdf0o1
  • 421
  • 6
  • 7
  • 7
    Python has an equivalent of both `echo` (`print`) and `sleep`, so it is actually not pythonic to go through external calls, especially when they are (non-portable) Unix calls. – Eric O. Lebigot Dec 17 '17 at 12:36
  • what does (3) means? – bumbumpaw Mar 20 '19 at 13:08
  • 1
    @bumbumpaw the `(3)` is passed to the lambda as the `x` argument. For this specific case, the "echo -n '\a';sleep 0.2;" string will be concatenated 3 time with itself generating the string "echo -n '\a';sleep 0.2;echo -n '\a';sleep 0.2;echo -n '\a';sleep 0.2;" before actual call to the `os.system` function. – Hemerson Tacon Jan 26 '22 at 16:15
21

I found this library to be helpful: Install beepy,

pip install beepy

There are 6 different sound options, you can see details here: https://pypi.org/project/beepy/

Code snip to listen to all the sounds:

import beepy as beep
for ii in range(1,7): 
    beep.beep(ii)
Brad123
  • 877
  • 10
  • 10
  • 1
    I had an issue with `winsound.Beep(....)` in w10 (I needed to run troubleshooter to solve it each time I run `winsound.Beep(....)`), but this solved it. – Minions Mar 15 '21 at 22:35
  • 1
    @user_007 I was also getting some errors after running it the first few times. I'm not sure what the problem was but I ended up bagging it and using '\a' instead. – Brad123 Mar 17 '21 at 00:20
  • On windows 10 in 2022, pip install beepy fails with error installing simpleaudio – tobi delbruck Dec 30 '22 at 15:26
12

The cross-platform way:

import time
import sys
for i in range(1,6):
    sys.stdout.write('\r\a{i}'.format(i=i))
    sys.stdout.flush()
    time.sleep(1)
sys.stdout.write('\n')

Thanks to c z:

print(end='\a')
FooBar167
  • 2,721
  • 1
  • 26
  • 37
10

If you want beep from Zelda or Mario theme :

!pip install chime
import chime
chime.theme('zelda')

chime.success()
chime.warning()
chime.error()
chime.info()
chime.notify_exceptions()

1/0
OrganicMustard
  • 1,158
  • 1
  • 15
  • 36
6

Using pygame on any platform

The advantage of using pygame is that it can be made to work on any OS platform. Below example code is for GNU/Linux though.

First install the pygame module for python3 as explained in detail here.

$ sudo pip3 install pygame

The pygame module can play .wav and .ogg files from any file location. Here is an example:

#!/usr/bin/env python3
import pygame
pygame.mixer.init()
sound = pygame.mixer.Sound('/usr/share/sounds/freedesktop/stereo/phone-incoming-call.oga')
sound.play()
Community
  • 1
  • 1
Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102
6

On linux: print('\007') will make the system bell sound.

Arghya Sadhu
  • 41,002
  • 9
  • 78
  • 107
Rodrigo
  • 103
  • 2
  • 6
3

I have made a package for that purpose.

You can use it like this:

from pybeep.pybeep import PyVibrate, PyBeep
PyVibrate().beep()
PyVibrate().beepn(3)
PyBeep().beep()
PyBeep().beepn(3)

It depends on sox and only supports python3.

qed
  • 22,298
  • 21
  • 125
  • 196
0

For all systems:

def beep():
  output.eval_js('new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgD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MgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=").play()')

beep()

Notebook developers must add a beep function to the output.

cconsta1
  • 737
  • 1
  • 6
  • 20
python.js
  • 21
  • 1
-3
# playsound in cross plate form, just install it with pip
#  first install playsound > pip install playsound
from playsound import playsound
playsound('audio.mp3')
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Wester king
  • 103
  • 1
  • 1
  • 5
  • 2
    While this can play the file `audio.mp3`, it doesn't really give an answer to the original question. – Steven Dec 03 '20 at 19:25