How to Have Beep Sound in Python

Fariba Laiq Feb 02, 2024
  1. Using the winsound Library to Make Beep Sound in Python
  2. Using pygame to Make Beep Sound in Python
  3. Using the Bell Character to Make Beep Sound in Python
How to Have Beep Sound in Python

The beep sound in python can be used in many situations. For Example, we can use that beep sound when scanning the barcode. Just like in shopping malls, when the salesman scans the product barcode, a beep sound rings, indicating that the barcode has been scanned successfully. There are many ways to do this task. Some of them are explained as follows.

Using the winsound Library to Make Beep Sound in Python

winsound is a built-in library in python (windows) that requires no installation. It’s a useful beep API that is used to play any sound. We can play our specified sound and can also generate the beep using its built-in method Beep(). In the Beep() function call, we can also specify the duration and frequency of the beep. To generate a beep using the winsound library, we will call its Beep() method, and inside this method call, we will specify the duration as one second and a frequency of 2000 Hz.

Example Code:

# Python 3.x
import winsound

frequency = 2000
duration = 1000
winsound.Beep(frequency, duration)

Using pygame to Make Beep Sound in Python

pygame is a cross-platform library containing many video game development modules. It has many modules for handling different kinds of media such as audio, video, and graphics. We can easily play any sound using this library’s mixer module.

We also have to specify our wav file for the beep sound here. First, we have to download any beep sound from the internet and upload it to our python environment directory. Using a jupyter notebook, we can easily upload that wav file in our home directory.

Example Code:

# Python 3.x
from pygame import mixer

mixer.init()
beep = mixer.Sound("bell.wav")
beep.play()

Using the Bell Character to Make Beep Sound in Python

One of the simplest ways to generate a beep sound is to use the bell character i-e '\a' within the print statement. This method does not require any extra package to import.

Note
This method does not work on every terminal or operating system.

Example Code:

# Python 3.x
print("\a")
Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn