使用文件对话框加载音频文件并使用 pygame 播放

Loading an audio file using file dialog and playing it with 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()

这只是 returns 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()

有关如何正确使用 mixer 模块的更多信息,请参阅 documentation