使用 PyQt6 播放声音
Playing sounds with PyQt6
随着 PyQt6 模块的发布,我开始将我的代码从 PyQt5 移植到 PyQt6。
在PyQt中,有一个叫做phonon的模块用来播放声音。
在 PyQt5 中,有一个名为 QMediaPlayer 的模块,用于播放声音。
现在,如何在PyQt6中播放声音?
有网站说QMediaPlayer还没有移植,应该在PyQt6版本的PyQt6.2中移植。
网站是这个 - https://www.pythonguis.com/faq/pyqt-pyside6-missing-modules/
该网站还表示 PyQt6.2 将于 2021 年 9 月发布。
导入重命名了吗?
需要注意的是:
在Qt6中如果你想播放一个音乐文件那么你有两个选择:
QSoundEffect
import sys
from PyQt6.QtCore import QUrl
from PyQt6.QtGui import QGuiApplication
from PyQt6.QtMultimedia import QSoundEffect
def main():
app = QGuiApplication(sys.argv)
filename = "sound.wav"
effect = QSoundEffect()
effect.setSource(QUrl.fromLocalFile(filename))
# possible bug: QSoundEffect::Infinite cannot be used in setLoopCount
effect.setLoopCount(-2)
effect.play()
sys.exit(app.exec())
if __name__ == "__main__":
main()
QMediaPlayer.
import sys
from PyQt6.QtCore import QUrl
from PyQt6.QtGui import QGuiApplication
from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer
def main():
app = QGuiApplication(sys.argv)
filename = "sound.mp3"
player = QMediaPlayer()
audio_output = QAudioOutput()
player.setAudioOutput(audio_output)
player.setSource(QUrl.fromLocalFile(filename))
audio_output.setVolume(50)
player.play()
sys.exit(app.exec())
if __name__ == "__main__":
main()
之前的 类 从 Qt 6.2 开始可用,此时 PyQt6 6.2.0 的 pypi 中没有可用的版本,但您可以从 Riverbank Computing PyPI Server 安装它存储库(有关详细信息,请参阅 here):
python -m pip install --index-url https://riverbankcomputing.com/pypi/simple/ --pre --upgrade PyQt6
可能几天后它就会在 pypi 中可用
随着 PyQt6 模块的发布,我开始将我的代码从 PyQt5 移植到 PyQt6。
在PyQt中,有一个叫做phonon的模块用来播放声音。
在 PyQt5 中,有一个名为 QMediaPlayer 的模块,用于播放声音。
现在,如何在PyQt6中播放声音?
有网站说QMediaPlayer还没有移植,应该在PyQt6版本的PyQt6.2中移植。
网站是这个 - https://www.pythonguis.com/faq/pyqt-pyside6-missing-modules/
该网站还表示 PyQt6.2 将于 2021 年 9 月发布。
导入重命名了吗?
需要注意的是:
在Qt6中如果你想播放一个音乐文件那么你有两个选择:
QSoundEffect
import sys from PyQt6.QtCore import QUrl from PyQt6.QtGui import QGuiApplication from PyQt6.QtMultimedia import QSoundEffect def main(): app = QGuiApplication(sys.argv) filename = "sound.wav" effect = QSoundEffect() effect.setSource(QUrl.fromLocalFile(filename)) # possible bug: QSoundEffect::Infinite cannot be used in setLoopCount effect.setLoopCount(-2) effect.play() sys.exit(app.exec()) if __name__ == "__main__": main()
QMediaPlayer.
import sys from PyQt6.QtCore import QUrl from PyQt6.QtGui import QGuiApplication from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer def main(): app = QGuiApplication(sys.argv) filename = "sound.mp3" player = QMediaPlayer() audio_output = QAudioOutput() player.setAudioOutput(audio_output) player.setSource(QUrl.fromLocalFile(filename)) audio_output.setVolume(50) player.play() sys.exit(app.exec()) if __name__ == "__main__": main()
之前的 类 从 Qt 6.2 开始可用,此时 PyQt6 6.2.0 的 pypi 中没有可用的版本,但您可以从 Riverbank Computing PyPI Server 安装它存储库(有关详细信息,请参阅 here):
python -m pip install --index-url https://riverbankcomputing.com/pypi/simple/ --pre --upgrade PyQt6
可能几天后它就会在 pypi 中可用