Coding Education STEM

Adding sound to Python code

Python isn’t necessarily for multimedia programming, so only recently I looked up ways to add audio in a Python script. Turns out there are several ways to do that. They’re all really simple.

Methods to add sound:

import winsound

fname = “soundfile.wav”
winsound.PlaySound(fname, winsound.SND_FILENAME)

import pygame
s = pygame.mixer.Sound(“soundfile.wav”)

# Start playback

# Stop playback

from pydub import AudioSegment
from pydub.playback import play

fname = “soundfile.wav”
mysong = AudioSegment.from_wav(fname)

from playsound import playsound
# wav works on all platforms. mp3 works on OS X. Other filetype/OS combos may work but have not been tested.

In all of the above methods, you can specify the full path to the “soundfile.wav” as in “c:\\myfolder\\soundfile.wav” (Yes, just like in C/C++, you need to add double slashes)

I found #1 method to be the easiest as on my Windows OS, it doesn’t require any special library installation.

In an earlier blog of mine, I showed the code to draw “dots” on screen randomly. So, here if I just add a popping sound to the dots appearing, it makes it so much better 🙂

The only code I added to that code shown in that blog is this:

import winsound 

fname = “pop1.wav”

And in my draw_random_dots() function, I added this line:

winsound.PlaySound(fname, winsound.SND_FILENAME)

That’s it. The satisfying result is this:

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top