在Python中在线程内运行的MP3播放模块

1 投票
1 回答
962 浏览
提问于 2025-04-16 17:24

我正在尝试写一个可以播放MP3的程序。这个程序还会有一个图形界面(GUI)。为了让这两个功能可以同时进行,我在使用线程。不过,我遇到了一个问题。每次运行我的程序时,所有的操作都正常进行,但就是没有声音出来。没有错误提示,什么都没有。感觉就像是播放的命令被跳过了一样。经过排查,我认为问题出在我在一个线程中运行音乐播放部分的代码(self.MP.controls.play())。

有没有人知道其他可以在线程中播放音乐的模块?或者有人知道可能是什么原因导致这个问题吗?

代码:

import GUIThread as GUIT # GUIThread is just an interface I made for the threading module, just act as if it was threading.  
from win32com.client import Dispatch

class Test :
    def __init__ (self) :
        self.Dir = r'song.mp3'
        self.Thread = GUIT.Thread(self, func=self.play_song, loop=False)
        self.MP = Dispatch('WMPlayer.OCX')
        song = self.MP.newMedia(self.Dir)
        self.MP.currentPlaylist.appendItem(song)

    def start (self) :
        # Starts the thread. 
        # Equivalent to :
        # t = threading.Thread(target=self.play_song)
        # t.start()
        self.Thread.start()

    def play_song (self) :
        # This whole function is done within the thread.

        if self.Dir != None :
            print self.Dir

            self.MP.controls.play()


    def protocol (self, val0, val1) :
        # Ignore this it's unrelated
        pass

T = Test()
T.start()

顺便说一下,我是在Windows 7上进行的。

补充:我还打算使用Tkinter作为图形界面工具包。

1 个回答

1

你可以试试 pymedia 或者 pyglet。我知道 pygame 也支持mp3格式。

撰写回答