如何在python 3.6中播放.wav文件?

时间:2017-12-09 19:24:15

标签: wav python-3.6 tkinter-canvas

目前,我正在使用python 3.6编写程序,并且按下按钮后我一直试图发出声音效果。我找到了一个来自不同问题的东西,发现here。下面是我的代码。

from tkinter import *

window = Tk()
c = Canvas(window, height=100, width=100, bg='blue')
c.pack()

with open('Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3 
Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
    data = base64.b64encode(f.read())

def playSound():
    sound = winsound.PlaySound(base64.b64decode(data), winsound.SND_MEMORY)

def sound(event):
    global sound
    if event.keysym == 'Up':
        playSound()
c.pack('<Key>', sound)

然后我收到此错误消息:

 RESTART: C:\Users\lenonvo\AppData\Local\Programs\Python\Python36\Python 3 
Files\Python 3.6.3\Test2.py 
Traceback (most recent call last):
  File "C:\Users\lenonvo\AppData\Local\Programs\Python\Python36\Python 3 
Files\Python 3.6.3\Test2.py", line 7, in <module>
    with open('Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 
3 Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
FileNotFoundError: [Errno 2] No such file or directory: 
'Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3 
Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav'

有什么建议吗?

另外,我不是一个高级的python编码器,所以如果你的答案可能过于简单,那将非常感激。 =]

现在修复了一个问题,感谢Patrick Artner,但现在出现此错误消息:

    data = base64.b64decode(f.read())
NameError: name 'base64' is not defined

1 个答案:

答案 0 :(得分:0)

这:

with open('Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3  Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:

是您的prog运行的相对路径。

使用

with open('C:/Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3 Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
          ^^^^