今天在网上看些教程时,发现有个实时录音与放音的话题,都在绞尽脑汁地想怎样将声音数据用QAudioInput录入文件,再从文件中用QAudioOutput输出播放,这样,往往出现一些问题。如在写入时是锁着的,只能等着写完关闭后再打开输出,这样就降低效率,造成时间差了,而且经常性打开关闭IO,也对硬盘有些损坏吧?这种一边写入一边读取的IO,是不是和C++中所说的队列相同?那么,哪个IO像队列呢?
我突然间想到,在网络部分的socket是不是很适合?
这样,我写了下面两个测试程序:
录制声音程序主要源码:
#include "dialog.h"
#include "ui_dialog.h"
#include <QAudioFormat>
#include <QHostAddress>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
clientSocket=new QTcpSocket;
//connect(clientSocket,SIGNAL(readyRead()),this,SLOT(readData()));
clientSocket->connectToHost(QHostAddress::LocalHost,1992);
}
void Dialog::on_pushButton_clicked()
{
QAudioFormat format;
// Set up the desired format, for example:
format.setSampleRate(8000);
format.setChannelCount(1);
format.setSampleSize(8);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
if (!info.isFormatSupported(format)) {
qWarning() << "Default format not supported, trying to use the nearest.";
format = info.nearestFormat(format);
}
audio = new QAudioInput(format, this);
//connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State)));
audio->start(clientSocket);
}
播放程序主要源码:
#include "dialog.h"
#include "ui_dialog.h"
#include <QAudioFormat>
#include <QAudioDeviceInfo>
#include <QTcpSocket>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
server= new QTcpServer;
server->listen(QHostAddress::LocalHost,1992);
connect(server, SIGNAL(newConnection()), this, SLOT(handlenewConnection()));
QAudioFormat format;
// Set up the format, eg.
format.setSampleRate(8000);
format.setChannelCount(1);
format.setSampleSize(8);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
if (!info.isFormatSupported(format)) {
qWarning() << "Raw audio format not supported by backend, cannot play audio.";
return;
}
audio = new QAudioOutput(format, this);
//connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State)));
socket =new QTcpSocket;
}
void Dialog::handlenewConnection()
{
qWarning("connected");
socket =server->nextPendingConnection();
audio->start(socket);
}
我是在笔记本上测试的,敲击话筒时,能在扬声器中听到声音,不过有一定量噪声,应该需要对录制的声音数据先进行降噪处理吧……