You will need to download WAV or MP3 Files for this lesson!! Go forth and search the internet!
You will need these 2 lines of code! This makes sure that your python file runs wherever you saved it. So, save python file and sounds to a directory, and they should all run perfectly fine!
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
Additional Change To VS Code
STEP 1:
Open VS Code.
STEP 2:
Press Ctrl + , (that’s Control + Comma) to open the Settings UI
Make sure to Press these all at once
OR click on File > Preferences > Settings (Windows)
OR Code > Preferences > Settings (Mac)
Step 3:
Enable "Execute in File Dir"
You’ll see this setting:
Python > Terminal: Execute In File Dir
Check the box ✅
This ensures when you run a Python file, the terminal's working directory is automatically changed to the folder where the file is saved.
This lesson introduces Pygame, a beginner-friendly Python library used to create games, multimedia applications, and interactive programs.
We're going to cover:
✅ What Pygame is and why it is useful
✅ Install and set up Pygame
✅ Create a menu system that lets them choose a theme song to play
✅ Use basic error checking to ensure smooth user input
Pygame is a library that helps Python programmers create games, animations, and multimedia applications.
It makes it easy to:
✔ Display graphics (e.g., images, shapes, animations)
✔ Play sounds and music 🎵
✔ Capture keyboard and mouse input 🎮
✔ Create interactive programs
It’s easy to learn
It’s used in real game development
It lets you experiment with programming in a fun way
Before diving into visual game development, we’ll start with something simpler but just as fun—sound!
In this mini-lesson, we’ll use Pygame to create a simple theme song player. The program will display a menu of songs, let the user choose one, and play the corresponding track. 🎶
This hands-on intro will help us learn Pygame step by step, setting the stage for more interactive projects in the future. 🚀
Pygame can reliably play the following formats:
WAV (.wav) – Uncompressed, high-quality, but large file size
MP3 (.mp3) – Compressed, small file size, but may not work on all systems
OGG (.ogg) – Similar to MP3, open-source, and better supported in Pygame
FLAC (.flac) – High-quality, lossless audio (not always needed for games)
MIDI (.mid) – Simple, small-size instrumental music files
LIMITATIONS:
MP3 files can sometimes have issues depending on the system, so if playback fails, try converting the file to OGG or WAV.
WAV files are large because they are uncompressed, so they are great for short sounds but not ideal for background music.
MIDI files don’t contain real audio, just instructions for playing notes (like a digital piano).
For this task, we're going to look at playing music (slightly longer files) using pygame. This is going to be different than quick sound effects, which we'll look at later. And, remember, we're on day 1, so only looking at the BASICS! There is a LOT more to playing audio/sound using Pygame!!
Before coding, we need to install Pygame.
Run this in Terminal (Mac/Linux) or Command Prompt (Windows)
If installed correctly, no errors will appear.
The Pygame mixer is a built-in sound and music manager that allows us to play, stop, and control audio files in Python programs.
Think of it like a DJ mixing board:
✔ It loads sound files (like MP3s or WAVs)
✔ It plays, pauses, and stops songs
✔ It adjusts volume and loops audio
Here's How To Set Up The Pygame Mixer:
pygame.mixer.init() – Sets Up the Mixer
Before playing any sounds, we must initialize the mixer. This prepares Pygame to handle audio. Think of this like you're turning on a music player, before hitting play
Here's How To Set Up The Pygame Mixer:
pygame.mixer.music.load(filename) – Loads a Song
We have to give a location for the file, or for now, PLACE IT IN THE SAME DIRECTORY as the PYTHON FILE
We then need to load the song using a built in method
This puts the file into memory
Remember, we're not streaming this like on YouTube, we have to load it before we can play!
pygame.mixer.music.play() – Plays the Loaded Song
Once the song is loaded into memory, we can play it.
This starts playing the loaded track from the beginning
4️⃣ pygame.mixer.music.stop() – Stops the Music
This immediately stops any music playing.
Remember, you need to download a song first! Look online, there are a lot of mp3 sites which you can access and download. Make sure it's APPROPRIATE!
Top Tier (1-5):
play(), load(), stop(), set_volume(), get_volume()
These are the bread-and-butter methods.
Almost every Pygame project with music uses these for basic playback control and volume adjustment.
Mid Tier (6-9):
pause(), unpause(), fadeout(), get_busy()
Common in interactive apps (e.g., games with pause menus or smooth audio transitions) but less universal than the top five.
Lower Tier (10-15):
queue(), get_pos(), rewind(), set_endevent(), set_pos(), get_endevent() are less frequently used.
They’re for specific needs like playlists, precise timing, or event handling, which aren’t always required in simple projects.
Setup:
load() is always paired with play() to start music.
Control:
stop(), pause(), unpause(), and fadeout() manage playback state with set_volume() tweaking the experience.
Info/Event:
get_busy(), get_pos(), set_endevent(), etc., are for advanced control or synchronization, less common in beginner projects.
Pygame will generate it's own set of errors called pygame.error
Methods that prepare audio playback, prone to file or system errors, requiring try/except.
Playback and adjustment methods, where pygame.error is common due to mixer state, and ValueError for bad arguments
Info: Safe methods returning data, typically not needing exception handling.
Advanced: Specialized methods with similar error risks to Setup, needing try/except for robustness
Remember, when you play a song, if the program ends, the music will stop!
If you want it to keep going, and finish, before the program ends, you need:
"Grab yer bell-bottoms and teased hair, coders, ‘cause we’re hoppin’ into the Retro TV Time Machine Jukebox! This ain’t no boring playlist—it’s a blast from the past with at least 8 iconic TV theme songs!!
Your mission: build a menu that lets me pick a tune and crank it up through me time-warped speakers! When I select a song, it plays—smooth as a vinyl record.
But if I’m ready to zap back to the menu, hittin’ ENTER better stop that groove pronto, or I’ll be stuck in the ‘80s forever! Oh, and if the files go missin’ or the sound glitches, don’t let this machine crash—handle it like a pro!"
Menu:
Display a numbered list of at least 8 TV theme songs (e.g., 1. "The Fresh Prince of Bel-Air," 2. "Friends," etc.).
Selection:
User enters a number to play the corresponding song using pygame.mixer.music.
Stop:
Pressing ENTER stops the current song and returns to the menu.
Error Handling: Use try/except to catch:
pygame.error (e.g., mixer not initialized, invalid file).
FileNotFoundError (e.g., missing audio file)
Display a funny retro-themed error message (e.g., "Whoa, dude, that tape’s totally busted!").
Files:
All MP3s/WAVs (e.g., fresh_prince.mp3, friends.mp3) must be in the same directory as the script.
BONUS:
Make the Jukebox Menu Awesome...
Fade In: Add a 500ms fade-in (play(fade_ms=500)) when starting the song for a cool effect.
Busy Check: Use get_busy() to warn if a song’s already playing