Some Questions about QMediaPlayer() in PyQt6

Question:

I’m trying to play sound with QMediaPlayer()

Code 1: this work fine.

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.

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!

Asked By: rdc

||

Answers:

After the player.play() method is called it exits the function and the media player is garbage collected. 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.

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())
Answered By: Alexander
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.