PyQt和py2exe:编译到.exe后,QSound没有声音



编译到exe后,我在用QSound.play()播放.wav声音时遇到问题(我使用的是Python 3.4.3、PyQt 5.4.1和py2exe 0.9.2.0)。

setup.py代码:

from distutils.core import setup
import py2exe
setup(
windows=[
    {
        "script": "main_app.py",
        "icon_resources": [(0, "favicon163248.ico")]
    }
],
data_files=[
    (
        'sounds', ['soundsSiren.wav']
    )
],
options={"py2exe": {"includes": ["sip"], "dist_dir": "MyProject"}}
)

我试过什么:

  1. 相对路径

    sound = QSound("sounds/Siren.wav") 
    sound.play() #works when simply running, doesn't work when compiling to exe
    
  2. 可执行文件(main_app.exe)的路径

    sound = QSound(os.path.dirname(sys.executable) + "soundsSiren.wav")
    sound.play() #doesn't work when compiling to exe
    
  3. 绝对路径

    sound = QSound("C:\path\to\project\MyProject\sounds\Siren.wav") 
    sound.play() #works when simply running, doesn't work when compiling to exe
    
  4. 资源

resources_qrc.qrc代码:

<RCC>
  <qresource prefix="media">
    <file>Siren.wav</file>
    <file>favicon163248.ico</file>
  </qresource>
</RCC>

然后用pyrcc5 转换为资源.py

from resources import *
...
sound = QSound(':/media/Siren.wav')
sound.play() #works when simply running, doesn't work when compiling to exe
  1. 将表单资源复制到动态硬盘

    QFile.copy(":/media/Siren.wav", "sounds/Siren.wav")
    sound = QSound("sounds/Siren.wav")
    sound.play() #still doesn't work after making exe!
    

在花了很多时间之后,我放弃了。

如有任何帮助,我们将不胜感激。

我使用python 2.7和cx_Freeze 4.3.1以及PyQt4

#-*- coding: utf-8-*-
__author__ = 'Aaron'
from cx_Freeze import setup, Executable
import sys
if sys.platform == "win32":
    base = "Win32GUI"

includefiles= ['icons','Sound','imageformats']

includes = ['sip', 'PyQt4.QtCore']

setup(
        name = u"Your Programe",
        version = "1.0",
        description = u"XXXX",
        options = {'build_exe': {'include_files':includefiles}},
        executables = [Executable("Your programe name.py" ,base = base, icon = "XXX.ico")])

我也遇到了同样的问题,使用Python 3.4.3、PyQt 5.5.1、py2exe 0.9.2.2。问题不在错误的文件路径中。

如果您拨打:

QAudioDeviceInfo.availableDevices(QAudio.AudioOutput)

从.exe,返回的列表将为空。

您应该将"sitepackages\PyQt5\plugins"中的foder:"\audio"添加到带有输出.exe文件的目录中,这样声音就可以工作了。

这是我的setup.py文件:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
from distutils.core import setup
import py2exe
import sys
import os, os.path
import zipfile
import shutil
def get_exe_name(f):
        dirname, filename = os.path.split(os.path.abspath(f))
        return os.path.split(dirname)[-1].lower()
def get_name(name):
        idx = name.find('.')
        if idx != -1:
                return name[:idx]
        return name
def build(__version__, __appname__, main_module = 'main.py', dest_base='main', icon='images\main.ico'):
        #exec('from ' + get_name(main_module) + ' import __version__, __appname__')
        try:
                shutil.rmtree('dist')
        except:
                print ('Cann't remove "dist" directory: {0:s}'.format(str(sys.exc_info())))
        if len(sys.argv) == 1:
                sys.argv.append('py2exe')
        options = {'optimize': 2,
        #       'bundle_files': 0, # create singlefile exe 0
                'compressed': 1, # compress the library archive
                'excludes': ['pywin', 'pywin.debugger', 'pywin.debugger.dbgcon', 'pywin.dialogs', 'pywin.dialogs.list', 'os2emxpath', 'optparse', 'macpath', 'tkinter'],
                'dll_excludes': ['w9xpopen.exe', 'mapi32.dll', 'mswsock.dll', 'powrprof.dll', 'MSVCP90.dll', 'HID.DLL'], # we don't need this
                'includes': ['sip', 'locale', 'calendar', 'logging', 'logging.handlers', 'PyQt5', 'PyQt5.QtCore', 'PyQt5.QtGui', 'PyQt5.QtMultimedia', 'PyQt5.QtNetwork', 'PyQt5.QtPrintSupport'],
                }
        #datafiles = [('platforms', ['C:\Python34\Lib\site-packages\PyQt5\plugins\platforms\qwindows.dll']),]
        import PyQt5
        datafiles = [('platforms', [PyQt5.__path__[0] + '\plugins\platforms\qwindows.dll']), ('audio', [PyQt5.__path__[0] + '\plugins\audio\qtaudio_windows.dll']),]
        dirs = ['images', 'docs', 'ssl', 'sounds', 'p2ini', 'lib', 'config']
        for d in dirs:
                try:
                        for f in os.listdir(d):
                                f1 = d + '\' + f
                                if os.path.isfile(f1): # skip directories
                                        datafiles.append((d, [f1]))
                except:
                        print ('Cann't find some files in directory "{0:s}": {1:s}'.format(d, str(sys.exc_info())))
        setup(version = __version__,
                description = __appname__,
                name = '{0:s} {1:s} application'.format(__appname__, __version__),
                options = {'py2exe': options},
                zipfile = None,
                data_files = datafiles,
                windows = [{'icon_resources':[(1,'images\main.ico')], 'script':main_module, 'dest_base':dest_base}] if icon else [{'script':main_module, 'dest_base':dest_base}],
                scripts = [main_module],
                #console = [{'icon_resources':[(1,'images\main.ico')], 'script':main_module, 'dest_base':dest_base}] if icon else [{'script':main_module, 'dest_base':dest_base}],
                )

调用setup.py函数的示例代码:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from setup import get_name, get_exe_name, build
MAIN_MODULE = 'main.py'
exec('from ' + get_name(MAIN_MODULE) + ' import __version__, __appname__')
build(__version__, __appname__, MAIN_MODULE, dest_base=get_exe_name(__file__))

最新更新