Redstomite
Redstomite

Reputation: 165

How to play sounds on python with tkinter

I have been working on a sort of 'Piano' on python. I have used tkinter as the ui, and this is how it goes:

from tkinter import*

tk =Tk()

btn = Button(tk, text="c note", command = play)

How do I define the function play to play a sound when I press it?
Please Help.

Upvotes: 3

Views: 18142

Answers (2)

Jaidee
Jaidee

Reputation: 1037

You can use pygame! It will not create a different window. Check out Pygame's official site for more amazing functions like getting length. There are two types of sound you can play sound or even music. Each supports pros and cons. Tkinter doesn't support audio. You can even use pyglet or other modules.

Example code:

import pygame
from tkinter import *
root = Tk()
pygame.init()
def play():
    pygame.mixer.music.load("Musics/example.mp3") #Loading File Into Mixer
    pygame.mixer.music.play() #Playing It In The Whole Device
Button(root,text="Play",command=play).pack()
root.mainloop()

Upvotes: 2

Parviz Karimli
Parviz Karimli

Reputation: 1287

Add these two pieces of code:

from winsound import *

&

command = lambda: Playsound("click_one.wav", SND_FILENAME)

If you don't like lambda then you can define a function before the creation of the button:

def play():
    return PlaySound("click_one.wav", SND_FILENAME)

You can also define a lambda function:

play = lambda: PlaySound("click_one.wav", SND_FILENAME)

Upvotes: 3

Related Questions