HiLos
HiLos

Reputation: 123

How to play a local video in a Qt Widgets Application, in Qt creator?

This is probably a very noob question... I am very new to Qt, and trying programming in Qt creator. Now I created a new Qt Widgets Application from Qt creator, and want to play a video with it. I now have the following 6 files in my project:

Where and how exactly should I write my code to make it play Demo.mp4 when I run my application (maybe using some tools called QVideoPlayer)? Should I add some Qwidget onto my videoplayer.ui? I now have four buttons "play", "pause", "full_screen" and "rearrange" on my videoplayer.ui. The result I want is something with features of:

Upvotes: 4

Views: 28349

Answers (2)

Mekap
Mekap

Reputation: 2085

What you are looking for is to implement a QMediaPlayer if you are on Qt 5, a QVideoPlayer if you are on Qt 4.4

For QMediaPlayer, you'll have to use a following implementation for adding one movie :

QMediaPlayer *player = new QMediaPlayer;
player->setMedia(QUrl::fromLocalFile("/users/somebody/somewhere/demo.mp4"));
player->setVolume(10);
player->play();

Upvotes: 2

dom0
dom0

Reputation: 7486

You are looking for Qt Multimedia Widgets. (You might need to install extra packages when running Linux).

The basic idea goes like this:

  • On the UI side of things you use a QVideoWidget. This is where the video is displayed.
    • This is what you would add to your .ui file.
    • Note the fullScreen property.
  • On the logic side of things you use a QMediaPlayer which controls what is played and when it's played.
    • The two are connected by calling QMediaPlayer::setVideoOutput(yourVideoWidgetGoesHere);.
    • Then you add a QMediaPlaylist to your QMediaPlayer.
    • Finally call QMediaPlayer::play() and you should be good to go

Then you want some basic controls if this works so far. QMediaPlayer provides the following slots that exactly do as their names suggest:

  • pause()
  • play()
  • stop()
  • setPosition(int), argument is in milliseconds. duration() might be of interest.
  • setVolume(int) and setMuted(bool). Volume goes from 0 to 100.
  • setPlaybackRate(double)
  • Metadata is available via metaData(QString key): http://qt-project.org/doc/qt-5/qmediaobject.html#metaData

Each of these also has a corresponding change signal, very interesting for you is probably the positionChanged(int) signal to update a slider or something similar with the current position.

Basic example courtesy of the Qt documentation:

player = new QMediaPlayer;

playlist = new QMediaPlaylist(player);
playlist->addMedia(QUrl("http://example.com/myclip1.mp4"));
playlist->addMedia(QUrl("http://example.com/myclip2.mp4"));

videoWidget = new QVideoWidget;
player->setVideoOutput(videoWidget);

videoWidget->show();
playlist->setCurrentIndex(1);
player->play(); 

Upvotes: 5

Related Questions