ArchersCat
ArchersCat

Reputation: 37

Importing and using mp3s on button press

So I have coded a "copy" of the game 2048 after following a Kite youtube tutorial. I want to add a small mp3 to play anytime you click an arrow key(to move stuff around in the game) but I'm not entirely sure what i'm doing right or wrong here. How do I do this? I've snipped the important stuff out(import music is a folder for my mp3s)

import tkinter as tk
import mp3play
import music

The two errors I'm getting are down below, the Tk in Tk() is underlined and the root in left(root...) when i attempt to run the code like this, it highlights "import mp3play" and says there is a Syntax error. Not sure why, I have in fact installed mp3play via pip installer as well

root = Tk()

f = mp3play.load('beep.mp3'); play = lambda: f.play()
button = left(root, text = "Play", command = play)
button.pack()
root.mainloop()

in between the 2 middle sections is the def for up, down, left, and right but that would just clutter this question

Here is the stackoverflow I've referenced for it, to be honest I dont understand half of it. How can I play a sound when a tkinter button is pushed?

Upvotes: 1

Views: 84

Answers (1)

Delrius Euphoria
Delrius Euphoria

Reputation: 15098

Take a look at this simple example using winsound which is easier to handle for small beeps.

from tkinter import *
import winsound

root = Tk()

def play():
    winsound.Beep(1000, 100)

b = Button(root,text='Play',command=play)
b.pack()

root.mainloop()

winsound.Beep(1000, 100) takes two positional arguemnts, 1000 is the frequency and 100 is the duration in milliseconds.

Do let me know if any errors or doubts.

Cheers

Upvotes: 1

Related Questions