I am experimenting (playing around) with the Python Tkinter Gui, and wondered if there is a way to play a sound like from a .wav or .au file?

Recommended Answers

All 2 Replies

To play sound on a Tkinter application you can use the module winsound. This module however works only on Windows computers. If you want to be more cross platform you can just combine Tkinter and PyGame ...

# play a sound on key press

from Tkinter import *
from pygame import mixer

def on_key(event):
    # detect any normal key press (0..9, A..Z, a..z)
    if event.char == event.keysym:
        if event.char == '1':
            # play the sound instance
            d1.play()
        if event.char == '2':
            d2.play()

prompt = 'Press key 1 or 2 to play a sound'

# initialize the pygame mixer
mixer.init(44100)

# pick sounds you have ...
# copy to working directory or indicate full path
try:
    # create the sound instances
    d1 = mixer.Sound("boing.wav")
    d2 = mixer.Sound("beep.wav")

except:
    prompt = "Error: Sound file not found"

root = Tk()
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow', fg='red')
label1.pack()
label1.bind_all('<Key>', on_key)

# start the event loop
root.mainloop()

You can download PyGame free from:
http://www.pygame.org/news.html

I downloaded and installed Pygame, got some of my soundfiles into the working directory and adjusted the sound file names in the program. Now it works great! Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.