import audio
SOUND = 'coin_pickup.wav' #@param ["clang.wav", "coin_pickup.wav", "correct.wav", "door.wav", "gameover.wav", "incorrect.wav", "laser.wav", "pop.wav", "thud.wav", "wood.wav", "zap.wav"]
audio.play(f'/sample_files/{SOUND}')
print(f'Played: {SOUND}')Sound — Audio, Music, and Speech
Sound turns a 3D scene from something you watch into something you experience. A click that plays a note, background music that sets a mood, speech that reacts to what the user does — all of this is possible with the audio module.
In this notebook you’ll learn how to play sound files, create notes and melodies, add sound effects to 3D shapes, and make your program speak out loud.
Playing a Sound File
The platform comes pre-loaded with a library of sound effects:
| File | Sounds like |
|---|---|
clang.wav |
Metal striking metal |
coin_pickup.wav |
Collecting a coin |
correct.wav |
Right answer chime |
door.wav |
Door opening |
gameover.wav |
Game over jingle |
incorrect.wav |
Wrong answer buzz |
laser.wav |
Sci-fi laser shot |
pop.wav |
Bubble pop |
thud.wav |
Heavy impact |
wood.wav |
Wood knock |
zap.wav |
Electric zap |
Use the dropdown to pick a sound and run the cell to hear it.
play() Is Blocking
audio.play() is blocking — your code pauses and waits for the sound to finish before moving to the next line. That’s why the print only appeared after you heard the sound.
audio.play('/sample_files/laser.wav') # ← code stops here until done
print('Done!') # ← only runs after the sound endsThis is useful for short effects you want to hear before continuing. Later you’ll see how to play sounds in the background so the scene keeps running at the same time.
{ “question_type”: “true_false”, “question”: “audio.play() returns immediately and lets the rest of the code continue while the sound plays.”, “answer”: “False”, “submitted_answer”: “” }
Playing Notes
audio.play_note(note, duration) plays a single musical note for a given number of seconds.
Note names use the format letter + optional accidental + octave number:
| Note | Meaning |
|---|---|
'C4' |
Middle C — the most common reference note |
'E4' |
E in the 4th octave |
'F#3' |
F sharp in the 3rd octave |
'Bb5' |
B flat in the 5th octave |
Higher octave numbers sound higher in pitch. 'C5' is one octave above 'C4'.
Run the cell and listen to the four notes in sequence.
import audio
audio.play_note('C4', 0.4) # middle C
audio.play_note('E4', 0.4) # a major third above C
audio.play_note('G4', 0.4) # a perfect fifth above C
audio.play_note('C5', 0.6) # same note, one octave higherMelodies and Chords
For a melody, audio.play_notes() is cleaner than calling play_note repeatedly. It takes a list of (note, duration) tuples and plays them in order:
audio.play_notes([
('C4', 0.3),
('E4', 0.3),
('G4', 0.6),
])To play several notes at the same time — a chord — pass a list of note names as the first argument to play_note:
audio.play_note(['C4', 'E4', 'G4'], 1.0) # C major chordRun the cell below to hear a short melody followed by a chord.
import audio
# A short melody
melody = [
('C4', 0.25), ('E4', 0.25), ('G4', 0.25), ('C5', 0.25),
('G4', 0.25), ('E4', 0.25), ('C4', 0.5),
]
audio.play_notes(melody)
# Finish with a C major chord — all three notes at once
audio.play_note(['C4', 'E4', 'G4'], 1.0){ “question_type”: “multiple_choice”, “question”: “Which line plays three notes at exactly the same time (a chord)?”, “options”: [ { “key”: “a”, “text”: “audio.play_notes([(‘C4’, 0.3), (‘E4’, 0.3), (‘G4’, 0.3)])” }, { “key”: “b”, “text”: “audio.play_note(‘C4’, 0.3) then audio.play_note(‘E4’, 0.3)” }, { “key”: “c”, “text”: “audio.play_note([‘C4’, ‘E4’, ‘G4’], 1.0)” }, { “key”: “d”, “text”: “audio.play(‘C4’, ‘E4’, ‘G4’)” } ], “answer”: “c”, “submitted_answer”: “” }
Background Music
So far every audio call has been blocking — the scene would have to wait for the music to finish before it could start. That’s the opposite of background music.
The platform includes three pre-recorded music tracks: music_ambience.wav, music_bach.wav, and music_sibelius.wav.
To start one while a scene runs, use await audio.play_async() instead of audio.play(). The keyword await tells Python: “kick this off, then keep going without waiting for it to finish.”
Use the dropdown to choose a track, then run the cell — the music starts and the scene loads at the same time.
import scene3d
import audio
TRACK = 'music_ambience.wav' #@param ["music_ambience.wav", "music_bach.wav", "music_sibelius.wav"]
scene = scene3d.Scene()
scene.set_sky('#0f3460')
scene.set_ground(length=10, width=10)
sphere = scene3d.Shapes.Sphere(diameter=1.5, segments=16)
sphere.set_color('#4488ff')
sphere.set_position(0, 0.75, 0)
scene.add(sphere)
ctx = scene.get_context('2d')
ctx.fill_style = '#ffffff'
ctx.font = '18px sans-serif'
ctx.fill_text(f'Now playing: {TRACK}', 10, 30)
await audio.play_async(f'/sample_files/{TRACK}') # starts music, continues immediately
scene.run()Sound Effects in a 3D Scene
Sound effects make interactions feel satisfying. You already know how on_click works — all you need to do is call audio.play() inside the handler.
The scene below has three shapes, each wired to a different sound effect. Click them and notice how the right sound makes each interaction feel distinct.
import scene3d
import audio
scene = scene3d.Scene()
scene.set_sky('#1a1a2e')
scene.set_ground(length=12, width=10)
ctx = scene.get_context('2d')
sounds = ['coin_pickup.wav', 'laser.wav', 'correct.wav']
colors = ['#e94560', '#f5a623', '#44cc88']
x_pos = [-3, 0, 3]
def make_handler(sound):
def handler():
audio.play(f'/sample_files/{sound}')
ctx.clear()
ctx.fill_style = '#ffffff'
ctx.font = '20px sans-serif'
ctx.fill_text(f'Played: {sound}', 10, 30)
return handler
for i in range(3):
s = scene3d.Shapes.Sphere(diameter=1.2, segments=16)
s.set_color(colors[i])
s.set_position(x_pos[i], 0.7, 0)
s.on_click(make_handler(sounds[i]))
scene.add(s)
ctx.fill_style = '#ffffff'
ctx.font = '20px sans-serif'
ctx.fill_text('Click a sphere!', 10, 30)
scene.run(){ “question_type”: “true_false”, “question”: “You can call audio.play() inside an on_click handler to play a sound when a shape is clicked.”, “answer”: “True”, “submitted_answer”: “” }
Text-to-Speech
audio.speak() converts any string into spoken words using the browser’s built-in voice engine. Like play(), it blocks until the speech finishes.
By default it uses an American English voice, but you can choose from many languages and accents using voice=audio.Voice.<LANGUAGE>.<GENDER>.
Run each cell and listen.
import audio
audio.speak('Hello! Welcome to the Python with 3D course.')import audio
# Different languages and voices
audio.speak('This is an Australian accent!', voice=audio.Voice.EN_AU.FEMALE)
audio.speak('Bonjour! Je parle avec une voix francaise.', voice=audio.Voice.FR_FR.MALE)
audio.speak('Hola! Esta es una voz espanola.', voice=audio.Voice.ES_ES.FEMALE){ “question_type”: “multiple_choice”, “question”: “Which call makes the computer speak in a British male voice?”, “options”: [ { “key”: “a”, “text”: “audio.speak(‘Hello’, language=‘British’)” }, { “key”: “b”, “text”: “audio.speak(‘Hello’, voice=audio.Voice.EN_GB.MALE)” }, { “key”: “c”, “text”: “audio.speak_british(‘Hello’, gender=‘male’)” }, { “key”: “d”, “text”: “audio.speak(‘Hello’, accent=‘EN_GB’)” } ], “answer”: “b”, “submitted_answer”: “” }
Try It Yourself
The scene below is a mini musical instrument — five spheres, each mapped to a note of the pentatonic scale. Click them in any order to play a tune. Every fifth note, the program announces your total out loud.
Use the slider to control how long each note rings.
import scene3d
import audio
NOTE_DURATION = 0.3 #@param {type:"slider", min:0.1, max:1.0, step:0.1}
scene = scene3d.Scene()
scene.set_sky('#0f3460')
scene.set_ground(length=18, width=10)
ctx = scene.get_context('2d')
notes = ['C4', 'D4', 'E4', 'G4', 'A4']
colors = ['#e94560', '#f5a623', '#4488ff', '#44cc88', '#cc44ff']
total_clicks = 0
spheres = []
def draw_hud():
ctx.clear()
ctx.fill_style = '#ffffff'
ctx.font = '20px sans-serif'
ctx.fill_text(f'Notes played: {total_clicks}', 10, 30)
def make_handler(idx):
def handler():
global total_clicks
total_clicks += 1
audio.play_note(notes[idx], NOTE_DURATION)
draw_hud()
if total_clicks % 5 == 0:
audio.speak(f'Nice! {total_clicks} notes played.')
return handler
for i in range(5):
s = scene3d.Shapes.Sphere(diameter=1.2, segments=16)
s.set_color(colors[i])
s.set_position(i * 3.5 - 7, 0.7, 0)
s.on_click(make_handler(i))
scene.add(s)
spheres.append(s)
draw_hud()
scene.run()Think about a game or experience where sound makes a big difference — a rhythm game, an adventure with narration, a puzzle with audio clues.
How would you add sound to the HUD mini-game from the previous notebook? What would you play when the timer runs out, when a new high score is reached, or when the player clicks a sphere? Describe how you would combine audio with what you already built.