关于Python使用playsound模块播放音频文件的编码问题UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position

Pascall ·
更新时间:2024-09-20
· 718 次阅读

由于项目的需要,需要播放声音。做过一些尝试,最简单的os.system(file),播放,出现错误提示一串乱码。
之后改成playsound尝试,刚开始几次效果不错。能直接播放,代码简单而优雅。之后出现的问题就让我悲剧加尴尬了。直接上我的代码和错误提示吧。

测试代码

# -*- coding: utf-8 -*- # @Author: Administrator # @Date: 2020-02-28 19:30:41 # @Last Modified by: Administrator # @Last Modified time: 2020-02-28 19:31:26 from playsound import playsound playsound('chuku.wav')

错误提示

Traceback (most recent call last): File "sound.py", line 8, in playsound('chuku.wav') File "D:\Program Files\Python38\lib\site-packages\playsound.py", line 35, in _playsoundWin winCommand('open "' + sound + '" alias', alias) File "D:\Program Files\Python38\lib\site-packages\playsound.py", line 30, in winCommand '\n ' + errorBuffer.value.decode()) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 0: invalid continuation byte ***Repl Closed***

错误提示
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xce in position 0: invalid continuation byte

出了问题得解决呀,所以第一时间使用搜索引擎来辅助我解决问题,搜遍百度,竟没有一个这种先例。这时有点失落了。
根据系统的错误定位,我们来看看源码是什么情况吧。

def winCommand(*command): buf = c_buffer(255) command = ' '.join(command).encode(getfilesystemencoding()) errorCode = int(windll.winmm.mciSendStringA(command, buf, 254, 0)) if errorCode: errorBuffer = c_buffer(255) windll.winmm.mciGetErrorStringA(errorCode, errorBuffer, 254) exceptionMessage = ('\n Error ' + str(errorCode) + ' for command:' '\n ' + command.decode() + '\n ' + errorBuffer.value.decode()) raise PlaysoundException(exceptionMessage) return buf.value

winCommand这个函数出错了
其中,
errorCode = int(windll.winmm.mciSendStringA(command, buf, 254, 0)),这一句代码出错了。抱歉,我看不懂是什么原因,还望大神来帮忙看看
最后插入全部的playsound代码,供各位大神分析,谢谢大家了。

class PlaysoundException(Exception): pass def _playsoundWin(sound, block = True): ''' Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on Windows 7 with Python 2.7. Probably works with more file formats. Probably works on Windows XP thru Windows 10. Probably works with all versions of Python. Inspired by (but not copied from) Michael Gundlach 's mp3play: https://github.com/michaelgundlach/mp3play I never would have tried using windll.winmm without seeing his code. ''' from ctypes import c_buffer, windll from random import random from time import sleep from sys import getfilesystemencoding def winCommand(*command): buf = c_buffer(255) command = ' '.join(command).encode(getfilesystemencoding()) errorCode = int(windll.winmm.mciSendStringA(command, buf, 254, 0)) if errorCode: errorBuffer = c_buffer(255) windll.winmm.mciGetErrorStringA(errorCode, errorBuffer, 254) exceptionMessage = ('\n Error ' + str(errorCode) + ' for command:' '\n ' + command.decode() + '\n ' + errorBuffer.value.decode()) raise PlaysoundException(exceptionMessage) return buf.value alias = 'playsound_' + str(random()) winCommand('open "' + sound + '" alias', alias) winCommand('set', alias, 'time format milliseconds') durationInMS = winCommand('status', alias, 'length') winCommand('play', alias, 'from 0 to', durationInMS.decode()) if block: sleep(float(durationInMS) / 1000.0) def _playsoundOSX(sound, block = True): ''' Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: http://stackoverflow.com/a/34568298/901641 I never would have tried using AppKit.NSSound without seeing his code. ''' from AppKit import NSSound from Foundation import NSURL from time import sleep if '://' not in sound: if not sound.startswith('/'): from os import getcwd sound = getcwd() + '/' + sound sound = 'file://' + sound url = NSURL.URLWithString_(sound) nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if not nssound: raise IOError('Unable to load sound named: ' + sound) nssound.play() if block: sleep(nssound.duration()) def _playsoundNix(sound, block=True): """Play a sound using GStreamer. Inspired by this: https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html """ if not block: raise NotImplementedError( "block=False cannot be used on this platform yet") # pathname2url escapes non-URL-safe characters import os try: from urllib.request import pathname2url except ImportError: # python 2 from urllib import pathname2url import gi gi.require_version('Gst', '1.0') from gi.repository import Gst Gst.init(None) playbin = Gst.ElementFactory.make('playbin', 'playbin') if sound.startswith(('http://', 'https://')): playbin.props.uri = sound else: playbin.props.uri = 'file://' + pathname2url(os.path.abspath(sound)) set_result = playbin.set_state(Gst.State.PLAYING) if set_result != Gst.StateChangeReturn.ASYNC: raise PlaysoundException( "playbin.set_state returned " + repr(set_result)) # FIXME: use some other bus method than poll() with block=False # https://lazka.github.io/pgi-docs/#Gst-1.0/classes/Bus.html bus = playbin.get_bus() bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE) playbin.set_state(Gst.State.NULL) from platform import system system = system() if system == 'Windows': playsound = _playsoundWin elif system == 'Darwin': playsound = _playsoundOSX else: playsound = _playsoundNix del system
作者:狼独舞



编码 byte IN position Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号