python-3.x - 使用文件对话框加载音频文件并使用 pygame 播放

标签 python-3.x tkinter pygame

我正在尝试使用 tkinter GUI 文件对话框加载一个文件,然后将其传递给另一个函数,该函数将使用 pygame 来播放它(尽管我愿意使用另一个包,如果它更容易的话),我将如何进行做这个?下面是代表我迄今为止所拥有的代码示例:

import tkinter, pygame
from tkinter import *
from pygame import *
from tkinter import filedialog

root = Tk()

def open_masker():
    global fileName
    fileName = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"),   ("All Files", "*.*")))
    masker_track = fileName
    if fileName =="": 
        fileName = None 
    else:
        fh = open(fileName, "r")
        fh.close()   


def masker_screen():
    global m_screen
    m_screen = Toplevel(root)
    m_screen.geometry('600x600')
    m_screen.transient(root) 
    m_label = Label(m_screen, text = "Playing New Masker Noise")
    m_label.pack(anchor = CENTER) 
    noise = pygame.mixer.Sound(file = fileName)
    noise.play(0, 5000)
    noise.stop()


b1 = Button(root, text = 'open file',command = open_masker).pack(anchor=CENTER)
b2 = Button(root, text = 'continue', command = masker_screen).pack(anchor = E)

root.mainloop()

这只是返回 pygame 无法加载文件的错误。这是因为它作为字符串加载到 fileName 变量中吗?如果是这样,我如何更改它并访问实际文件?

谢谢!

最佳答案

好的,我已经解决了您遇到的一些问题,这是我完整的工作解决方案(请参阅代码中的注释以获取解释):

import pygame
from tkinter import *  # not advisable to import everything with *
from tkinter import filedialog

pygame.mixer.init() # initializing the mixer

root = Tk()

audio_file_name = ''

def open_masker():
    global audio_file_name
    audio_file_name = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"),   ("All Files", "*.*")))

def masker_screen():  
    # we will also use the audio_file_name global variable
    global m_screen, audio_file_name  

    m_screen = Toplevel(root)
    m_screen.geometry('600x600')
    m_screen.transient(root) 
    m_label = Label(m_screen, text = "Playing New Masker Noise")
    m_label.pack(anchor = CENTER)

    if audio_file_name: # play sound if just not an empty string
        noise = pygame.mixer.Sound(audio_file_name)
        noise.play(0, 5000)

b1 = Button(root, text = 'open file',command = open_masker)
# does not make sense to call pack directly 
# and stored the result in a variable, which would be None
b1.pack(anchor=CENTER)

Button(root, text = 'continue', command = masker_screen).pack(anchor = E)

root.mainloop()

参见documentation有关如何正确使用 mixer 模块的更多信息。

关于python-3.x - 使用文件对话框加载音频文件并使用 pygame 播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27962133/

相关文章:

python-3.x - 通过Wit.ai运行mysql查询

python - 如何增加文本小部件中的字体大小?

python - 在 Tkinter Canvas 中移动球

python - 使用 python 的 OpenGL 屏幕截图

python - 如何在按键时连续移动pygame中的表面?

python - 我似乎无法使用控件让我的 Sprite 旋转

python - 带 GUI 的 Pi 相机预览 - Raspberry Pi

Python - 类型(名称、基础、字典)

python - 如何在python中将html转换为文本?

python - Tkinter(Python 3.5): TypeError when calling `.configure` on a label object