How To Add And Play Sound In Python Codes

play sound in python img

LEARN HOW TO ADD AND PLAY SOUND IN PYTHON CODES.

Have you ever wondered how you could add or play sound in python projects or codes you created? It sounds like fun right? Well wonder no more, this simple project will teach how to do that, and you’ll even learn how to do a couple more tricks.

We’ll use a previous project we built to explore this new project, but we’ll focus more on add and play sound in python and other new concepts like Threading in python and the playsound module.

ANY REQUIRED KNOWLEDGE?

The difficulty rate for this particular guessing game with python is beginner/medium and what’s required is not that much, once you already know the basics of python like lists, importing of libraries/modules/package, python scope, indentation, input, while loop, try and except, and a few other similar concepts, then this should be fun..

WHAT YOU’LL LEARN IN THIS PROJECT.

  • How to use the playsound module to add and play sound in python projects
  • How to start and run different threads in python
  • How to use the randint from random library.
  • Python operators
  • How to get information from user and assign them to variables
  • Using of while loops
  • How to eliminate and control possible errors from user’s end instead of showing the usual error code.

NOW LET’S CODE..

We are going to use one of our previous project, we’ll use The Number Guessing Game project, you might need to review the project again to be sure you understood the codes properly before continuing with the add and play sound in python tutorial.

The codes for playing sound(Extra code that is not on the previous project)

Firstly we need to import the necessary libraries:

#let's import the necessary libraries, we'll use randint to generate random numbers
#We'll use playsound module to play sounds
#we'll use threading to run new and parrellel threads
from playsound import playsound
import threading

Now let’s make two functions, one for just playing sounds and one for playing sounds in background while other codes executes simultaneously (using a new thread)

#let's make some necessary functions
#if the sound files are in the same folder with your main code, then you can just put the "file name.wav/mp3" according to the file extension without adding directory.
def play_sound(file, repeat):
    """This function takes a sound name and play it the number of times you selected"""
    for _ in range(repeat):
        playsound('/[your sound file directory]/'+file)
        if (diff_level == 0 or guessed_num == hidden_num):
            break

Using playsound module is super easy! You just install the module, then import and use module: playsound(file.wav) It supports both mp3 and wav files. To install, just use pip install playsound.

#let's create another function which we will use to run play sounds in background using a new thread
def start_thread(sound, rps):
    """This function plays a sound in the background using a new thread"""
    end_sound = threading.Thread(target = play_sound, args = (sound, rps), daemon = True).start()

We play a sound in a new thread when we want the sound to play in the background while other codes are executing. The reason for using new thread is because: if we don’t use a new thread, other codes must have to wait for the sound to finish playing before executing and this is not what we want all the time, though we allowed such at a few places where background sounds weren’t necessary in the codes. You might have to do a little googling on threading to fully understand how it works.

OTHER EXTRA CODES:

Other extra codes that weren’t present in the previous Number Guessing Game project which we added in this project are:

We used more try and except to track and control more possible error that could arise, like if a user mistakenly enters something else other than number while guessing, the error will be caught and a while loop will keep prompting the user to do the right thing instead of completely stopping the game and displays the usual error codes.

THE FINAL CODE:

Now let’s see how to use those created functions, the added try and except codes, and fun of adding and playing sound in python:

# let's import the necessary libraries, we'll use randint to generate random numbers
#We'll use playsound module to play sounds
#we'll use threading to run new and parrellel threads
from random import randint
from playsound import playsound
import threading


#let's make some necessary functions
#let's make this somewhat fun by adding some sounds, we'll create a sound function

def play_sound(file, repeat):
    """This function takes a sound name and play it the number of times you selected"""
    for _ in range(repeat):
        playsound('/[your sound file directory]/'+file)
        if (diff_level == 0 or guessed_num == hidden_num):
            break

#let's create another function which we will use to run play sounds in background using a new thread
def start_thread(sound, rps):
    """This function plays a sound in the background using a new thread"""
    end_sound = threading.Thread(target = play_sound, args = (sound, rps), daemon = True).start()
        


#let's set up some variables for the game
diff_level = 0
diff_choice = ''
diff_response = ['easy', 'hard']
hidden_num = randint(1,200)
guessed_num = 0




#let's make sure the user is entering the required string for difficulty level to avoid error
#let's also get user preferred difficulty level as well
#we'll also play some sounds while at it.
play_sound('intro.wav',1)
play_sound('welcome-geofspot.wav', 1)
while diff_choice not in diff_response:
    diff_choice = input('Hey! choose a difficulty level, please type in either "easy" or "hard" only:\n').lower()
if diff_choice == 'easy':
    diff_level = 15
else:
    diff_level = 5
    

#let's communicate to the user his/her choice and how the game works
play_sound('hmm.wav', 1)
print(f'Great! You have chosen {diff_choice}, which means you can guess up to and not more than {diff_level} times, let the game🤩 begin! ')
#print(f'the hidden number was {hidden_num}')


#let's make sure the user enters the required input and also capture the user input

while True:
    try:
        guessed_num = int(input('A number between 1 and 200 has been marked, guess the marked number🤔:\n'))
    except:
        print('Please make sure you entered integers only, you may select between 1 and 200')
    else:
        print('Nice try')
        play_sound('nasal-laugh.wav',1)
        break

#let's keep running the game until the user chances finishes or until the user guesses the marked number right
while guessed_num != hidden_num:
    diff_level -= 1
    if diff_level == 0:
        print(f'Your chances are now {diff_level}, you have exhausted all your chances, the marked number was {hidden_num} 🙁GAME OVER!')
        play_sound('laugh.wav', 1)
        break
        
    if diff_level == 2:
        start_thread('suspense.wav', 20)
        print('Start thinking harder now')
        
    if diff_level == 7:
        start_thread('yawn.wav', 1)
        
    if diff_level == 8:
        start_thread('sneeze.wav', 1)
        
        
    while True:
        try:
            if guessed_num > hidden_num:
                play_sound('scifi_glitch.wav',1)
                guessed_num = int(input(f' 🚫 The number: {guessed_num} is incorrect and higher than the marked number, you now have {diff_level} chances left \n Guess again:'))


            if guessed_num < hidden_num:
                play_sound('scifi_glitch.wav',1)
                guessed_num = int(input(f' 🚫 The number: {guessed_num} is incorrect and less than the marked number, you now have {diff_level} chances left \n Guess again:'))
        except:
            print('Please make sure you entered integers only, you may select between 1 and 200')
        else:
            break


    
else:
    print(f'Wow! You are awesome! 😍 You guessed right, the marked number was actually {hidden_num}')
    start_thread('light-cheer.wav', 1)

All the codes are inside the last code shown above so you can see how they were structured, the scopes and all.

At line 52 you can uncomment the code to see the hidden number each time you play the game.

To get free commercial-use sounds for your project, you may click here or you do a little googling on free sound effects.

If you happen to run into any puzzle don’t hesitate to write me, or leave a comment at comment section.

You may also stay connected with our updates on our telegram channel.

We have not added the replit link for you to run and test this code yet, because there were some issues with package installations for this code on replit for the sound to be implemented but the code will surely run on your local system or production once you successfully installed and can use the playsound module, I have already tested it on mine. However once we are able to run it on replit or similar place we’ll update this tutorial with the link.

🤞 Don’t miss the tips!

We don’t spam! Read more in our privacy policy

Geoff

Geoff is a software engineer, web content specialist, tech private trainer and an IT virtual assistant.

This Post Has One Comment

Leave a Reply