Python使用playsound播放音频报错:MCI无法识别指定设备
解决playsound库播放gTTS生成MP3时的Error 263问题
问题场景
使用gTTS将文本转换为MP3文件后,调用playsound库播放时触发Error 263,提示「指定设备未打开或不被MCI识别」。
实现代码
import playsound # to play an audio file import random import os from gtts import gTTS # google text to speech # get string and make a audio file to be played def speak(audio_string): tts = gTTS(text=audio_string, lang='en-in') # text to speech(voice) r = random.randint(1,20000000) # random name audio_file = 'audio-' + str(r) + '.mp3' # audio file name tts.save(audio_file) # save as mp3 playsound.playsound(audio_file) # play the audio file os.remove(audio_file) # remove audio file speak("how can I help you")
报错信息
Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32 Error 263 for command: open audio-14004851.mp3 The specified device is not open or is not recognized by MCI. Error 263 for command: close audio-14004851.mp3 The specified device is not open or is not recognized by MCI. Failed to close the file: audio-14004851.mp3 Traceback (most recent call last): File "C:/Users/Sanctuary/Desktop/VAVO/test.py", line 19, in <module> speak("how can I help you") File "C:/Users/Sanctuary/Desktop/VAVO/test.py", line 14, in speak playsound.playsound(audio_file) # play the audio file File "C:\Users\Sanctuary\AppData\Local\Programs\Python\Python310\lib\site-packages\playsound.py", line 72, in _playsoundWin winCommand(u'open {}'.format(sound)) File "C:\Users\Sanctuary\AppData\Local\Programs\Python\Python310\lib\site-packages\playsound.py", line 64, in winCommand raise PlaysoundException(exceptionMessage) playsound.PlaysoundException: Error 263 for command: open audio-14004851.mp3 The specified device is not open or is not recognized by MCI.
解决方案
1. 降级playsound版本
新版playsound(1.3.0+)在Windows系统上存在MCI兼容性问题,降级到稳定旧版即可解决:
pip uninstall playsound pip install playsound==1.2.2
2. 使用音频文件绝对路径
相对路径可能导致MCI无法定位文件,修改代码使用绝对路径播放:
# 在tts.save(audio_file)之后添加 audio_file = os.path.abspath(audio_file) playsound.playsound(audio_file)
3. 替换为其他音频播放库
如果playsound问题持续,改用pygame或simpleaudio替代:
- 示例(pygame):
先安装pygame:pip install pygame
修改speak函数的播放逻辑:import pygame pygame.mixer.init() pygame.mixer.music.load(audio_file) pygame.mixer.music.play() while pygame.mixer.music.get_busy(): pygame.time.Clock().tick(10)
4. 检查系统音频设备
- 确认系统默认音频设备未被禁用,可在「声音设置」中切换默认设备后重试
- 重启Windows音频服务:按下Win+R输入
services.msc,找到「Windows Audio」服务重启
内容的提问来源于stack exchange,提问作者Abhijeet
相关产品推荐
相关产品推荐

