#include <QApplication>
#include <QAudioSource>
#include <QAudioSink>
#include <QMediaDevices>
#include <QAudioFormat>
#include <QByteArray>
#include <QIODevice>
#include <QDebug>
#include <QUdpSocket>
#include <QLabel>
#include <QPixmap>
#include <QVBoxLayout>
#include <QTimer>
#include <QCoreApplication>
#include <QtMultimedia>
#include <QThread>
QUdpSocket udpSocket;
quint16 port = 5021; // 你要监听的端口
class AudioHandler : public QObject {
Q_OBJECT
public:
AudioHandler() {
// 设置音频格式
QAudioFormat format;
format.setSampleRate(16000); // 采样率 16kHz
format.setChannelCount(1); // 单声道
format.setSampleFormat(QAudioFormat::Int16); // 16 位 PCM 格式
// 获取默认输入和输出设备
QAudioDevice inputDevice = QMediaDevices::defaultAudioInput();
QAudioDevice outputDevice = QMediaDevices::defaultAudioOutput();
// 检查设备是否支持所需格式
if (!inputDevice.isFormatSupported(format)) {
qWarning() << "Requested format not supported by input device, using nearest format.";
format = inputDevice.preferredFormat();
}
if (!outputDevice.isFormatSupported(format)) {
qWarning() << "Requested format not supported by output device, using nearest format.";
format = outputDevice.preferredFormat();
}
// 初始化音频输入和输出
audioInput = new QAudioSource(inputDevice, format, this);
audioOutput = new QAudioSink(outputDevice, format, this);
// 创建输入和输出设备流
inputDeviceStream = audioInput->start();
outputDeviceStream = audioOutput->start();
// 连接输入流数据读取槽函数
connect(inputDeviceStream, &QIODevice::readyRead, this, &AudioHandler::handleAudioInput);
}
private slots:
void handleAudioInput() {
#if 1
qDebug() << "handleAudioInput123";
QByteArray audioData = inputDeviceStream->read(2900); // 读取4096字节
// 发送数据通过UDP
QHostAddress targetAddress("192.168.1.101"); // 替换为目标设备的实际 IP 地址
quint16 targetPort = 5022; // 目标端口
qint64 bytesSent = udpSocket.writeDatagram(audioData, targetAddress, targetPort);
if (bytesSent == -1) {
qDebug() << "Failed to send UDP datagram:" << udpSocket.errorString();
} else {
qDebug() << "Sent" << bytesSent << "bytes to" << targetAddress.toString() << "on port" << targetPort;
}
#endif
// QByteArray audioData = inputDeviceStream->readAll(); // 从输入流读取音频数据
outputDeviceStream->write(audioData); // 将数据写入输出流播放
}
private:
QAudioSource *audioInput;
QAudioSink *audioOutput;
QIODevice *inputDeviceStream;
QIODevice *outputDeviceStream;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
AudioHandler audioHandler;
return app.exec();
}
#include "main.moc"