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

时间:2015-01-15 11:14:01

标签: 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变量中吗?如果是这样,我该如何更改并访问实际文件?

谢谢!

1 个答案:

答案 0 :(得分:2)

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

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