How can i make a sound in python?

17,172

Solution 1

You can try 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').

Even Windows has its own 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: Link to Python Winsound Library

Solution 2

First: What is your OS? According to the documentation winsound "access to the basic sound-playing machinery provided by Windows platforms". So winsound only works on Windows, so if you're a LINUX or UNIX you have to find another way.

Seconds: What to you mean by "make a sound" if you just want a "beep" you can use beep and call it with os.system from os module (or subprocess) like this:

import os

os.system('play --no-show-progress --null --channels 1 synth %s sine
%f' %( 0.1, 400))

You have to install beep (it's an "advanced" pc-speaker beeper), the installation depend on your system Mac/OSX, Linux(Ubuntu/Debian, Fedora, Archlinux), BSD? on Ubuntu/Debian: sudo apt-get install beep

Update #2 @shahar Well according to the doc you did the right thing.

You can catch error that python raise to you to figure it out what's wrong

try:
    import winsound
    winsound.Beep(400, 1000)
except RuntimeError:
    print("The system is not able to beep the speaker")
except ImportError:
    print("Can't import winsound module")

The code above work on python2.7 and python3 but in case, what's your python version? I used python3.5.3 on windows and the code work like a charm.

Share:
17,172
shahar
Author by

shahar

Updated on June 04, 2022

Comments

  • shahar
    shahar almost 2 years

    I tried to make a sound with the winsound libry and my system doesnt recognize it... Can I write a code in python that makes a sound without installing a new libraries?

    I searched some solutions but all I found doesnt work. I need a library that included in the python package.

    import winsound
    winsound.Beep(300,2000)