0

我正在尝试制作一个能够播放、停止、暂停和恢复歌曲的简单音频播放器。

我想要做什么

  • 在单独的线程上运行音频,然后能够使用主线程中的 MCI 来暂停和恢复它。

什么不起作用

  • 当尝试使用线程或多处理调用函数来播放歌曲时,MCI 返回一个值为 263 的错误代码(不幸的是,我无法在网上找到任何关于数字错误代码的文档)并立即结束整个程序。

有什么作用

  • 在不使用线程/多处理的情况下播放、暂停和恢复。

我的代码

from ctypes import windll
import threading
import time

class WinPlayAudio():
    def __init__(self):
        self.alias = "A{}".format(id(self))

    def _MCI_command(self,command):
        windll.winmm.mciSendStringW(command,0,0,0) # If printed, this returns 263 == unrecognized audio device

    # This does not play anything even tho wait is turned to: True
    def _play(self, start=0, wait = False):
        th = threading.Thread(target=self._MCI_command, args=(f'play {self.alias} from {start} {"wait" if wait else ""}',))
        th.start()

    def _open_song(self, audio_path):
        self._MCI_command(f'open {audio_path} alias {self.alias}')
    
    def _set_volume(self):
        self._MCI_command(f'setaudio {self.alias} volume to 500')

    def _pause(self):
        self._MCI_command(f'pause {self.alias}')

    def _resume(self):
        self._MCI_command(f'resume {self.alias}')

    def _stop(self):
        self._MCI_command(f'stop {self.alias}')
    

if __name__ == '__main__':
    p = WinPlayAudio()
    p._open_song(r"D:\songs\bee.mp3")
    p._play(0, True)
4

1 回答 1

0

固定代码 如果您希望多线程,请远离别名

import threading
from ctypes import windll


class WinPlayAudio():
    def __init__(self):
        self.alias = "A{}".format(id(self))
        self.audio_path = ""

    def _MCI_command(self, command):
        print(command)
        err = windll.winmm.mciSendStringW(command, 0, 0, 0)  # If printed, this returns 263 == unrecognized audio device
        print(err)

    def _play(self, start=0, wait=True):
        th = threading.Thread(target=self.__play__, args=(start, wait))
        th.start()

    def __play__(self, start, wait):
        self._MCI_command(f'play {self.audio_path} from {start} {"wait" if wait else ""}', )

    def _open_song(self, audio_path):
        self.audio_path = audio_path
        self._MCI_command(f'open {audio_path} alias {self.alias}')

    def _set_volume(self):
        self._MCI_command(f'setaudio {self.alias} volume to 500')

    def _pause(self):
        self._MCI_command(f'pause {self.alias}')

    def _resume(self):
        self._MCI_command(f'resume {self.alias}')

    def _stop(self):
        self._MCI_command(f'stop {self.alias}')


if __name__ == '__main__':
    p = WinPlayAudio()
    p._open_song("start.mp3")
    p._play()
于 2021-08-17T23:38:05.497 回答