Qt C++實現錄屏錄音功能的示例詳解
錄屏部分
錄屏的主要思路為抓取屏幕截圖,然后將其合成視頻。抓取屏幕若使用qt自帶的抓屏會出現抓不到鼠標的問題,所以應重寫抓屏:
static QPixmap grabWindow(HWND winId, int x, int y, int w, int h) { RECT r; GetClientRect(winId, &r); if (w < 0) w = r.right - r.left; if (h < 0) h = r.bottom - r.top; HDC display_dc = GetDC(winId); HDC bitmap_dc = CreateCompatibleDC(display_dc); HBITMAP bitmap = CreateCompatibleBitmap(display_dc, w, h); HGDIOBJ null_bitmap = SelectObject(bitmap_dc, bitmap); BitBlt(bitmap_dc, 0, 0, w, h, display_dc, x, y, SRCCOPY | CAPTUREBLT); CURSORINFO ci; ci.cbSize = sizeof(CURSORINFO); GetCursorInfo(&ci); if ((ci.ptScreenPos.x > x) && (ci.ptScreenPos.y > y) && (ci.ptScreenPos.x < (x + w)) && (ci.ptScreenPos.y < (y + h))) DrawIcon(bitmap_dc, ci.ptScreenPos.x - x, ci.ptScreenPos.y - y, ci.hCursor); // clean up all but bitmap ReleaseDC(winId, display_dc); SelectObject(bitmap_dc, null_bitmap); DeleteDC(bitmap_dc); QPixmap pixmap = QtWin::fromHBITMAP(bitmap); DeleteObject(bitmap); return pixmap; }
這樣抓取的圖片會包括鼠標。
但是,如果直接while循環(huán)進行抓屏的話,一秒頂多抓10幀。所以應該啟動一個計時器,按照想要的幀率進行抓屏??上В琎t的計時器會有各種各樣的限制,所以我自己實現了計時器進行處理:
#pragma once #include <iostream> #include <string> #include <thread> #include <chrono> #include <atomic> #include <memory> #include <condition_variable> using namespace std; class STTimer { public: ~STTimer(void); template<class F> STTimer(F func):m_func(func){}; void Start(unsigned int secd,bool isBimmediately_run = false); void Stop(); void SetExit(bool b_exit); private: // 私有數據部分 std::atomic_bool m_bexit; std::atomic_bool m_bimmediately_run; // 是否立即執(zhí)行 unsigned int m_imsec; // 間隔時間 std::function<void()> m_func; // 執(zhí)行函數 std::thread m_thread; std::mutex m_mutex; std::condition_variable m_cond; void Run(); };
#include "STTimer.h" #include "ScreenController.h" #include <QDebug> STTimer::~STTimer(void) { } void STTimer::Start(unsigned int sec, bool bim_run) { m_bexit.store(false); m_imsec = sec; m_bimmediately_run.store(bim_run); m_thread = std::thread(std::bind(&STTimer::Run,this)); } void STTimer::Stop() { m_bexit.store(true); m_cond.notify_all(); // 喚醒線程 if (m_thread.joinable()) { m_thread.join(); } } void STTimer::SetExit(bool b_exit) { m_bexit.store(b_exit); } void STTimer::Run() { if(m_bimmediately_run.load()) { if(m_func) { m_func(); } } while(!m_bexit.load()) { qDebug()<<"runmning"; std::unique_lock<std::mutex> locker(m_mutex); m_cond.wait_for(locker,std::chrono::milliseconds(m_imsec),[this](){return m_bexit.load(); }); if(m_func) { m_func(); } } if(m_bexit.load()) { return; } }
這樣,就可以多線程進行抓屏了,合成視頻我使用的是avilib,理論上它可以同時合成音頻,但合成后除了potplayer都無法解碼,所以僅用它做合成視頻。
void ScreenController::getOneFrame() { int ids = curController->getId(); controlIds(false, ids); std::thread t1(startThread,ids); t1.detach(); } void ScreenController::startThread(int ids) { QPixmap mp = grabWindow((HWND)QApplication::desktop()->winId(), curController->curRect.x(), curController->curRect.y(), curController->curRect.width(), curController->curRect.height()); QByteArray ba; QBuffer bf(&ba); mp.save(&bf, "jpg", 100); char* framBf = ba.data(); int byteLen = ba.length(); qDebug()<<byteLen; QMutexLocker lockeer(&curController->m_smutex2); AVI_write_frame(curController->avfd, framBf, byteLen, 1); lockeer.unlock(); controlIds(true, ids); }
在停止錄屏時,需要判斷抓屏線程是否結束,很多人會想到線程池,其實不必那么復雜,只需為每個線程綁定一個獨立的id,然后操作含有這個id的列表即可。
void ScreenController::controlIds(bool isDelete, int index) { QMutexLocker locker(&curController->m_smutex); if (isDelete) { int ind = curController->ids.indexOf(index); curController->ids.removeAt(ind); } else { curController->ids.push_back(index); } }
錄音部分
錄音部分其實非常簡單,僅需使用qt的模板即可實現:
QAudioDeviceInfo info = QAudioDeviceInfo::availableDevices(QAudio::AudioInput).at(macIndex); recorder = new QAudioRecorder(this); QAudioEncoderSettings settings = recorder->audioSettings(); settings.setCodec("audio/PCM"); // 這些是QAudioRecorder是設置,見名思意 settings.setBitRate(96000); //settings.setSampleRate(44100); settings.setChannelCount(2); settings.setQuality(QMultimedia::EncodingQuality::HighQuality); settings.setEncodingMode(QMultimedia::ConstantQualityEncoding); recorder->setAudioSettings(settings); recorder->setAudioInput(info.deviceName()); recorder->setOutputLocation(QUrl::fromLocalFile(fileName)); recorder->setContainerFormat("audio/wav"); recorder->record();
合成部分
合成我使用的是ffmpeg進行視頻合成。僅需傳入參數即可。
void CaptureController::MakeVideo() { if(curController->isMakingVideo) { return; } qDebug()<<"making video"; curController->isMakingVideo = true; QString program = QCoreApplication::applicationDirPath(); program += "/ffmpeg.exe"; qDebug()<<"program"; qDebug() << program; QProcess process; QStringList arguments; arguments << "-i" << curController->voicefileName << "-i" << curController->screenfileName << "-s" << QString::number(curController->screenRect.width()) + "x" + QString::number(curController->screenRect.height()) <<"-b:v" << "40000k" << curController->finalfileName;//傳遞到exe的參數 qDebug() << arguments; process.start(program, arguments); process.waitForFinished(); QFile f1(curController->voicefileName); QFile f2(curController->screenfileName); f1.remove(); f2.remove(); curController->isMakingVideo = false; }
轉成動態(tài)庫
有時我們很想將這個功能提供給其他人使用,但是其他人未必使用qt,甚至未必使用C++,那么就需要將其封裝成動態(tài)庫。但是,qt的消息機制是十分獨立的,在沒有QApplication::exec()的時候,或者說沒有發(fā)起qt獨立的消息循環(huán)機制的時候,他的信號槽機制將不會起作用。比如這個錄音模塊,在直接提供給他人使用的時候將不會錄制到任何聲音。所以需要對錄音部分進行封裝。
class MCCtClass:public QThread{ public: MCCtClass(); void startTestingMac(int index); int getCurrentVoice(); void startCapVoice(int index); void stopThread(); void setFileName(QString name); protected: virtual void run(); private: volatile bool isStop; int macIndex; int currentRun; QEventLoop *lp; MacController *ct; QString fileName; };
MCCtClass::MCCtClass() { currentRun = -1; ct = nullptr; } void MCCtClass::startCapVoice(int index) { currentRun = 1; macIndex = index; this->start(); } void MCCtClass::startTestingMac(int index) { currentRun =2; macIndex = index; this->start(); } void MCCtClass::setFileName(QString name) { fileName = name; } void MCCtClass::run() { ct = new MacController(); if(currentRun == 1) { ct->SetFileName(fileName); ct->StartRecordingVoice(macIndex); lp = new QEventLoop(); lp->exec(); } else if(currentRun == 2) { qDebug()<<"run2"; ct->StartTestingMac(macIndex); lp = new QEventLoop(); lp->exec(); } } int MCCtClass::getCurrentVoice() { if(ct == nullptr) { return 0; } return ct->getTestVolume(); } void MCCtClass::stopThread() { lp->exit(); lp->deleteLater(); if(currentRun == 1) { ct->StopRecordingVoice(); } else if(currentRun == 2) { ct->StopTestingMac(); } ct->deleteLater(); ct = nullptr; }
使用qthread派生出一個獨立的麥克風操作類,在run函數中啟動一個獨立的消息循環(huán),這樣麥克風的錄制功能就可以進行了。
關于動態(tài)庫的封裝,用到了傳說中的QMFCAPP,這個大家百度一下隨便下載一個就可以,但這樣封裝還有問題,因為別人未必有qt環(huán)境,所以我對它進行了二次封裝。相信各位也有其他的解決辦法。
完整項目
我做的demo提供了額外的麥克風檢測和屏幕檢測功能,同時也提供了視頻合成進度檢查的接口,喜歡的朋友可以下載進行參考。
完整的項目和msvc_2012版本的動態(tài)庫可以復制下面的鏈接進行下載:
鏈接:https://pan.baidu.com/s/1eBtLfE21rZ545T7rrmmXpg
提取碼:qg1h
到此這篇關于Qt C++實現錄屏錄音功能的示例詳解的文章就介紹到這了,更多相關Qt C++錄屏錄音內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C語言中l(wèi)seek()函數和fseek()函數的使用詳解
這篇文章主要介紹了C語言中l(wèi)seek()函數和fseek()函數的使用詳解,是C語言入門學習中的基礎知識,需要的朋友可以參考下2015-08-08