如何让PyQt5的QWebEngineView可以播放音频?

How to make QWebEngineView of PyQt5 able to play audio?

我想使用 PyQt5 的 QWebEngineView 在网络上播放音频。这是我的代码:

import sys

from PyQt5 import QtWebEngineWidgets, QtWidgets

if __name__ == '__main__':
    app = QtWidgets.QApplication([])

    view = QtWebEngineWidgets.QWebEngineView()
    view.settings().setAttribute(QtWebEngineWidgets.QWebEngineSettings.PluginsEnabled, True)
    view.settings().setAttribute(QtWebEngineWidgets.QWebEngineSettings.JavascriptEnabled, True)

    html = '''
    <html>
        <audio id="pron" src="http://static.sfdict.com/staticrep/dictaudio/A06/A0612000.mp3"></audio>
        <button onclick="document.getElementById('pron').play()">Play!</button>
    </html>'''
    view.setHtml(html)

    view.resize(250, 150)
    view.move(300, 300)
    view.show()

    sys.exit(app.exec_())

但是当我点击Play按钮时,音频没有播放。我怎么了?

QWebEngineView doesn't support mp3 playback by default ,至少在我测试过的 Win7 上是这样。如果您将 mp3 url 更改为 ogg 格式(默认情况下通过 QWebEngineView 支持 ogg 格式),例如

https://upload.wikimedia.org/wikipedia/commons/5/5a/Nl-URL%27s.ogg

那么你的例子就可以了!

当我在网上搜索时,我发现启用mp3播放的唯一方法是编译我们自己的Qt webengine,someone told me the way to do it如下,

Compile your own Qt (including QtWebEngine), then compile PyQt and when calling its configure.py, use --qmake to pass the path to the correct qmake executable.

如果有人对编译 Qt webengine 感兴趣,这些信息可能会有帮助