python中使用playsound函数是出现以下报错:

    Error 263 for command:
        open D:/Python_code/Chatting_robot/py1/mp3/hello.mp3
    指定的设备未打开,或不被 MCI 所识别。

    Error 263 for command:
        close D:/Python_code/Chatting_robot/py1/mp3/hello.mp3
    指定的设备未打开,或不被 MCI 所识别。
Failed to close the file: D:/Python_code/Chatting_robot/py1/mp3/hello.mp3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Hasee\AppData\Local\Programs\Python\Python310\lib\site-packages\playsound.py", line 72, in _playsoundWin
    winCommand(u'open {}'.format(sound))
  File "C:\Users\Hasee\AppData\Local\Programs\Python\Python310\lib\site-packages\playsound.py", line 64, in winCommand
    raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException:
    Error 263 for command:
        open D:/Python_code/Chatting_robot/py1/mp3/hello.mp3
    指定的设备未打开,或不被 MCI 所识别。

看中间报错文件位置为:

C:\Users\Hasee\AppData\Local\Programs\Python\Python310\lib\site-packages\playsound.py

在电脑中找到文件并打开
找到报错的64行左右,会看到如下一个函数:

def winCommand(*command):
        bufLen = 600
        buf = c_buffer(bufLen)
        command = ' '.join(command) .encode('utf-16')
        errorCode = int(windll.winmm.mciSendStringW(command, buf, bufLen - 1, 0))  # use widestring version of the function
        if errorCode:
            errorBuffer = c_buffer(bufLen)
            windll.winmm.mciGetErrorStringW(errorCode, errorBuffer, bufLen - 1)  # use widestring version of the function
            exceptionMessage = ('\n    Error ' + str(errorCode) + ' for command:'
                                '\n        ' + command.decode('utf-16') +
                                '\n    ' + errorBuffer.raw.decode('utf-16').rstrip('\0')
                                )
            logger.error(exceptionMessage)
            raise PlaysoundException(exceptionMessage)
        return buf.value

因为python3默认的是utf-8的编码方式,而不是utf-16.
找到如上代码第4行

 command = ' '.join(command) .encode('utf-16')

注释掉:encode(‘utf-16’)

command = ' '.join(command) 		#.encode('utf-16')

最终如下:
在这里插入图片描述

所以这个报错不是声卡的问题,连续报错了几天,突发奇想想到了去看一眼playsound的源码为什么报错,结果一眼看到了它的编码方式竟然是utf-16,没想到问题出在这,改完就可以了。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐