[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky]
[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Start and stop background music in Windows with Python

[This example uses winsound to start and stop background music in Windows with Python]

Note that winsound only works in Windows.

This example is pretty simple. When you click Start, the program starts playing a repeating piece of background music and changes the button's text to Stop. When you click Stop, it stops the music and restores the button's text to Start.

The following code starts the music.

def start_sound(self): # Play the UFO sound asynchronously in a loop. winsound.PlaySound('ufo.wav', winsound.SND_LOOP | winsound.SND_ASYNC)

This code calls winsound.PlaySound, passing it the sound file's name. The winsound.SND_LOOP | winsound.SND_ASYNC parameter makes the sound repeat and run asynchronously.

The following code stops the music.

def stop_sound(self): # Stop the UFO sound. winsound.PlaySound(None, 0)

This code simply calls winsound.PlaySound, passing it no sound file to stop all playing sounds.

When you click the button, the program executes the following code.

def start_click(self): if self.playing: # Stop the music. self.start_button.config(text='Start') self.stop_sound() else: # Start the music. self.start_button.config(text='Stop') self.start_sound() self.playing = not self.playing

This code starts or stops the music and updates the button's text.

IMPORTANT: Be sure to stop any music before the program ends or the music will continue to play indefinitely. That also happens if the program crashes, so be sure it doesn't!

For more information about winsound, see the winsound documentation.

© 2024 Rocky Mountain Computer Consulting, Inc. All rights reserved.