简体   繁体   English

PyQt6中关于QMediaPlayer()的一些问题

[英]Some Questions about QMediaPlayer() in PyQt6

I'm trying to play sound with QMediaPlayer()我正在尝试使用QMediaPlayer()播放声音

Code 1 : this work fine.代码 1 :这项工作正常。

import sys

from PyQt6.QtCore import QUrl
from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer
from PyQt6.QtWidgets import QApplication

app = QApplication([])

filename = "src/2.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())

Code 2 but this have no voice.代码 2但这没有声音。

import sys

from PyQt6.QtCore import QUrl
from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer
from PyQt6.QtWidgets import QApplication

app = QApplication([])

def play_it():
    filename = "src/2.mp3"
    player = QMediaPlayer()
    audio_output = QAudioOutput()
    player.setAudioOutput(audio_output)
    player.setSource(QUrl.fromLocalFile(filename))
    audio_output.setVolume(50)
    player.play()

play_it()
sys.exit(app.exec())

I can't find what make differences here.我在这里找不到有什么不同。 Thanks for your help sincerely!衷心感谢您的帮助!

After the player.play() method is called it exits the function and the media player is garbage collected.player.play()方法后,它退出 function 并且媒体播放器被垃圾收集。 You will need to keep a reference to the player by returning it if you would like it to live beyond the scope of the function call.如果您希望它在 function 调用的 scope 之外存在,则需要通过返回来保留对player的引用。

for example:例如:

import sys

from PyQt6.QtCore import QUrl
from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer
from PyQt6.QtWidgets import QApplication

app = QApplication([])

def play_it():
    filename = "src/2.mp3"
    player = QMediaPlayer()
    audio_output = QAudioOutput()
    player.setAudioOutput(audio_output)
    player.setSource(QUrl.fromLocalFile(filename))
    audio_output.setVolume(50)
    return player

player = play_it()
player.play()
sys.exit(app.exec())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM