Python Beep

  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

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')
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.