
#PLAY SOUND PYTHON HOW TO#
Hint: it might help to look at the pygame.mixer methods for determining if sound is being played (or "mixed") and how to stop a sound. For code examples, you can check out onhold and ding, or scroll down to the Usage section. It includes a synchronous API and an equivalent asynchronous API that is compatible with asyncio and trio. Also, because we can, have the LED light up while the sound is playing. playsounds provides a simple cross-platform API to play sounds in Python scripts. When you press it again, the sound clip starts over again. Let's fix this! Change the code so that when you press the button while the sound is playing, the sound stops. language:pythonĬhallenge: You might have noticed that if you press the button again while the sound is playing, an new sound will start that overlaps the first clip. play() method in our Sound object to start playing the. Our downloaded file, applause-1.wav is used to create a Sound object, which we store in the sound variable. Later in our code, we can use the mixer module to create a Sound object with: language:python We will use the command line to download a. This says that we want to import the mixer module from the pygame package. Downloading audio clips and playing them on a Raspberry Pi is quite simple. For example, we might say: language:python To use it, we just need to use from pygame in our code, and we can specify which module we want to use by saying import after it. Lucky for us, pygame comes pre-installed with Python on Raspbian. A package in Python is a collection of modules grouped together. To play sounds, we are using the pygame package.
#PLAY SOUND PYTHON INSTALL#
Troubleshooting: If you see the message "ModuleNotFoundError: No module named 'pygame'" you will need to install the pygame package by entering pip install pygame in a terminal. Push the button, and you should hear some congratulatory sounds! applause.py), and start the program with python applause.py. # When you press ctrl+c, this will be called If (current_state = False) and (prev_state = True): # Remember the current and previous button states In a new file, enter the following code: language:python In a terminal, enter the following: language:bash Raspbian Lite does not come with some Python packages pre-installed).


Code: Push Button, Get Soundĭepending on your version of Raspbian, you may or may not have to install the pygame package (e.g. You should hear some nice cheering and clapping out of your speaker (or headphones).

Test playing this sound with: language:bash Download a free sound clip (we'll go with some applause, because we're awesome): language:bash
