After we have learned how to capture a still image from our camera, let's proceed to learn how to record videos as well. First, open mainwindow.h and add the following variables:
private: Ui::MainWindow *ui; QCamera* camera; QCameraViewfinder* viewfinder; QCameraImageCapture* imageCapture; QMediaRecorder* recorder; bool connected; bool recording;
Next, open mainwindow.ui again and right-click on the Record button. Choose Go to slot... from the menu and select the clicked() option, then, click the OK button. A slot function will be created for you; then proceed to add the following code into the slot function:
void MainWindow::on_recordButton_clicked() { if (connected) { if (!recording) { recorder = new QMediaRecorder(camera); camera->setCaptureMode(QCamera::CaptureVideo); recorder->setOutputLocation(QUrl(qApp-
>applicationDirPath())); recorder->record(); recording = true; } else { recorder->stop(); recording = false; } } }
This time, we use a QMediaRecorder for recording video instead. We must also set the camera's capture mode to QCamera::CaptureVideo before calling recorder->record().
To check the error message produced by the media recorder during the recording stage, you may connect the error() signal of the media recorder to a slot function like this:
void MainWindow::on_recordButton_clicked() { if (connected) { if (!recording) { recorder = new QMediaRecorder(camera); connect(recorder, SIGNAL(error(QMediaRecorder::Error)),
this, SLOT(recordError(QMediaRecorder::Error))); camera->setCaptureMode(QCamera::CaptureVideo); recorder->setOutputLocation(QUrl(qApp-
>applicationDirPath())); recorder->record(); recording = true; } else { recorder->stop(); recording = false; } } }
Then, simply display the error message in the slot function:
void MainWindow::recordError(QMediaRecorder::Error error) { qDebug() << errorString(); }
Do note that, at the time of writing this chapter, the QMediaRecorder class only supports video recording on macOS, Linux, mobile platforms and Windows XP. It doesn't work on Windows 8 and Windows 10 at the moment, but it will be ported over in one of the upcoming versions. The main reason is that Qt is using Microsoft's DirectShow API to record video on the Windows platform, but it has since been deprecated from the Windows operating system. Hopefully, by the time you're reading this book, this feature has been completely implemented in Qt for Windows 8 and 10.
If it hasn't, you may use third-party plugins that use OpenCV API for recording video, such as the Qt Media Encoding Library (QtMEL) API, as a temporary solutions. Do note that the code used in QtMEL is completely different than the one we're showing here in this chapter.