基于QT和UDP实现一个实时RTP数据包的接收,并将数据包转化成文件

简单介绍:代码写的比较详细,需要留意的地方看结尾介绍

头文件

#ifndef RTPRECEIVER_H
#define RTPRECEIVER_H

#include 
#include 
#include 
#include 
#include 
#include 


class RTPReceiver : public QWidget
{
    Q_OBJECT
public:
    explicit RTPReceiver(QWidget *parent = nullptr);
    ~RTPReceiver();
    void start();
    void closeFile();
    void writeBufferToFile();
    void initSocket();
    void sendGetRequest();


private slots:
    void readPendingDatagrams();


private:
    QUdpSocket *udpSocket;
    QFile file;
    QByteArray buffer;
    int bufferSize = 1400;
    QString filePath;
};

#endif // RTPRECEIVER_H

cpp文件

#include "rtpreceiver.h"


const int RTP_HEADER_LENGTH = 12;

RTPReceiver::RTPReceiver(QWidget *parent)
    : QWidget(parent)
{
    this->setVisible(false);

}

RTPReceiver::~RTPReceiver()
{


}

void RTPReceiver::start()
{

    initSocket();

}

void RTPReceiver::closeFile()
{
    if (file.isOpen()) {
        file.close();
    }

}



void RTPReceiver::readPendingDatagrams()
{


    qDebug()<<"readPendingDatagrams方法被执行";
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(), datagram.size());

         qDebug()<<"传过来的大小"<= bufferSize) {
               writeBufferToFile();
               continue;
           }

           //代表是最后一次请求
           if(buffer.size()<1666){
                writeBufferToFile();

                //关闭文件
                closeFile();
                udpSocket->close();

                //调用whisper去翻译当前音频
                RequestWhisper();

                //重新初始化服务
                initSocket();

                continue;
           }

    }

}


void RTPReceiver::writeBufferToFile()
{
    qDebug()<<"每次写入大小"<bind(QHostAddress::AnyIPv4, 1234); // 替换成实际的RTP端口
    if(!bindResult)
    {
        qDebug()<<"绑定失败";
        return;
    }

    //绑定接收
     qDebug()<<"RTP服务监听中";
    connect(udpSocket, &QUdpSocket::readyRead, this, &RTPReceiver::readPendingDatagrams);
}




注意: 这里需要注意的地方是,如何判断数据包是否是最后一包,这里当时我花了一些时间,最后采取通过判断数据包大小来判断是否是最后一包,我定义的发送的RTP的数据包缓存大小是1400,然后如果小于这个大小,说明是最后一包,这样就可以执行文件关闭和一些其他命令了,还有其他的不同的方式,这里需要你们自己去了解RTP数据包

你可能感兴趣的:(c++的学习历程,qt,udp,开发语言)