在我的PySide应用程序中,我使用以下代码来播放wav文件:
media = Phonon.MediaObject()
audio = Phonon.AudioOutput(Phonon.MusicCategory)
Phonon.createPath(media, audio)
alarm_file = 'alarm_beep.wav'
f = QtCore.QFile(alarm_file)
if f.exists():
source = Phonon.MediaSource(alarm_file)
if source.type() != -1: # -1 stands for invalid file
media.setCurrentSource(source)
media.play()
else:
logger.debug('Alert media missing: %s' % alarm_file)
当我运行Python脚本时,这在Ubuntu中运行良好但是当我使用Pyinstaller for windows将应用程序编译为exe时,声音不会播放。
我使用以下pyinstaller命令
pyinstaller --onefile --add-data "alarm_beep.wav;." main.py
尝试添加媒体文件,但无济于事。
控制台中的例外是
WARNING: bool __cdecl Phonon::FactoryPrivate::createBackend(void) phonon backend plugin could not be loaded
WARNING: bool __cdecl Phonon::FactoryPrivate::createBackend(void) phonon backend plugin could not be loaded
WARNING: bool __cdecl Phonon::FactoryPrivate::createBackend(void) phonon backend plugin could not be loaded
WARNING: bool __cdecl Phonon::FactoryPrivate::createBackend(void) phonon backend plugin could not be loaded
WARNING: Phonon::createPath: Cannot connect MediaObject ( no objectName ) to AudioOutput ( no objectName ).
Alert media missing: alarm_beep.wav
很明显它好像" alarm_beep.wav"不存在。
不确定为什么add-data
命令没有处理它?</ p>
答案 0 :(得分:1)
捆绑应用程序后,外部文件将保存在临时目录中,您需要参考该目录。有关引用这些外部文件的讨论,请参阅this post。简而言之,您需要在引用之前更新资源文件的路径:
#resource_path is the relative path to the resource file, which changes when built for an executable
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath('.')
return os.path.join(base_path, relative_path)
并在您的代码正文中:
alarm_file = resource_path('alarm_beep.wav')