QT开发中文网

play rtsp stream using libmpv in Qt

Here is an example of how to play an RTSP stream using libmpv in Qt:

  1. First, you need to install the libmpv library in your system.

  2. In your Qt project, add the libmpv library to your .pro file:

LIBS += -lmpv
  1. Create a QWidget (e.g., QFrame) to act as a container for the video player.

  2. In the constructor of your QWidget subclass, create an instance of libmpv and set its options:

#include <mpv/client.h>
#include <mpv/render_gl.h>

class VideoPlayer : public QFrame {
   Q_OBJECT

public:
   VideoPlayer(QWidget *parent = 0);
   ~VideoPlayer();

private:
   mpv_handle *mpv;
};

VideoPlayer::VideoPlayer(QWidget *parent)
   : QFrame(parent)
{
   mpv = mpv_create();
   mpv_set_option_string(mpv, "vo", "gpu");
   mpv_set_option_string(mpv, "hwdec", "auto");
   mpv_initialize(mpv);
}
  1. To play the RTSP stream, use the mpv_command function with the loadfile command and the URL of the stream:
void VideoPlayer::play(const QString &url)
{
   const char *cmd[] = {"loadfile", url.toUtf8().constData(), NULL};
   mpv_command(mpv, cmd);
}
  1. Finally, create a GL widget (e.g., QOpenGLWidget) to display the video output and attach it to the libmpv instance:
class VideoOutput : public QOpenGLWidget {
   Q_OBJECT

public:
   VideoOutput(QWidget *parent = 0);
   ~VideoOutput();

protected:
   virtual void paintGL();

private:
   mpv_handle *mpv;
   mpv_opengl_cb_context *mpv_gl;
};

VideoOutput::VideoOutput(QWidget *parent)
   : QOpenGLWidget(parent)
{
   mpv = ((VideoPlayer*) parentWidget())->mpv;
   mpv_gl = mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB);
   mpv_opengl_cb_set_update_callback(mpv_gl, VideoOutput::onUpdate, this);
}

void VideoOutput::paintGL()
{
   mpv_opengl_cb_draw(mpv_gl, defaultFramebufferObject(), width(), -height());
}
  1. Connect the widget to the player UI:
class MainWindow : public QMainWindow {
   Q_OBJECT

public:
   MainWindow();

private slots:
   void onPlay();
   void onStop();

private:
   VideoPlayer *player;
   QLineEdit *urlInput;
   QPushButton *playButton;
};

MainWindow::MainWindow()
{
   player = new VideoPlayer(this);
   urlInput = new QLineEdit(this);
   playButton = new QPushButton("Play", this);

   QVBoxLayout *layout = new QVBoxLayout();
   layout->addWidget(player);
   layout->addWidget(urlInput);
   layout->addWidget(playButton);

   QWidget *widget = new QWidget(this);
   widget->setLayout(layout);
}

void MainWindow::onPlay()
{
   QString url = urlInput->text();
   player->play(url);
}

void MainWindow::onStop()
{
   mpv_command(player->mpv, (const char*[]){"stop", NULL});
}

That’s it! Now you can use the MainWindow class to create a window with a video player that can play RTSP streams using libmpv.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=608

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?