No video and only audio output when restarting QMediaPlayer's media

108 Views Asked by At

I'm currently developing an application using Qt 5.15.2 on Ubuntu 22.04 and encountering an issue with QMediaPlayer in a video playback context. I've provided my code below for reference.

The application successfully plays, pauses, and resumes video playback.

However, when a video reaches its end and I attempt to restart it, only the audio resumes — the video display does not.

This issue occurs specifically after the video has completed playing, and I try to replay it.

// videoPlayer function
void MainWindow::videoPlayer() {
    player = new QMediaPlayer(this);
    videoWidget = new QVideoWidget(ui->widget_video);
    player->setVideoOutput(videoWidget);
    player->setMedia(QUrl::fromLocalFile("/home/ubuntu/Desktop/test.mp4"));

    QVBoxLayout *layout = new QVBoxLayout(ui->widget_video);
    layout->addWidget(videoWidget, 0, Qt::AlignCenter);
    layout->setMargin(0);
    layout->setSpacing(0);
    ui->widget_video->setLayout(layout);
}

// Button click event handler
void MainWindow::on_pushButton_video_status_clicked() {
    switch (player->state()) {
    case QMediaPlayer::PlayingState:
        player->pause();
        break;
    case QMediaPlayer::PausedState:
        player->play();
        break;
    case QMediaPlayer::StoppedState:
        player->setPosition(0); // Reset to start
        player->play();
        break;
    default:
        player->play();
        break;
    }
}

I've tried resetting the media player's position and reinitializing the media source, but the issue persists. The audio resumes as expected, but the video display remains blank.

How can I solve this?

1

There are 1 best solutions below

4
On

I've now resolved this problem by directly placing the QVideoWidget in the parent widget, without using a layout. Here's the updated code:

void MainWindow::videoPlayer() {
    player = new QMediaPlayer(this);
    video = new QVideoWidget; // Create a new QVideoWidget

    // Set the size and position of the QVideoWidget
    video->setGeometry(5, 5, ui->groupBox_videoPlayer->width() - 10, ui->groupBox_videoPlayer->height() - 10);
    video->setParent(ui->groupBox_videoPlayer); // Set the parent widget

    player->setVideoOutput(video); // Set the video output
    player->setMedia(QUrl::fromLocalFile("/home/ubuntu/Desktop/test.mp4")); // Load the media file

    video->setVisible(true); // Make the QVideoWidget visible
    video->show(); // Show the QVideoWidget
}

This change allows the video widget to be placed directly inside the parent widget, avoiding issues that arose from using a QVBoxLayout.

However, I couldn't understand why I was encountering problems when I used

QVBoxLayout.