Wednesday, April 24, 2024
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:

1.
import winsound

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

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

# Start playback
s.play()

# Stop playback
s.stop()

3.
from pydub import AudioSegment
from pydub.playback import play

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

4.
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.
playsound(“soundfile.wav”)

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