在Qt4.6中新加入了QtMultimedia模块来提供一些底层的多媒体功能,比如音频的采集和回放、频谱分析、操作视频帧等。该模块主要由8个类组成,这些类及其功能介绍如表13-3所。
在QtMultimedia模块中与音频控制相关的类有QAudioFormat、QAudioDeviceInfo、QAudioInput和QAudioOutput。其中,QAudioFormat类用来存储音频参数信息,音频格式指定了一个音频流中的数据怎样被排列,可以在音频流上使用codec()来指定编码。除了编码,QAudioFormat还包含了频率、声道数量、样本大小、样本类型和字节顺序等参数,如表13-4所列。
使用QtMultimedia模块,需在工程文件中添加如下一行代码:
QT+ = multimedia
下面通过一个音频录制与播放的例子来进一步熟悉这些类的应用。
只写主要的代码:
开始录制按钮的槽函数中:
void MainWindow::slot_startRecording()
{
m_btnPlay->setDisabled(true);
m_btnRecord->setDisabled(true);
m_file.setFileName("test.raw");
m_file.open(QIODevice::WriteOnly|QIODevice::Truncate);
// set wave format: include sampling rate, WORD nChannels, sample size, encoding, byte-order, sample type
QAudioFormat format;
format.setFrequency(8000);
format.setChannels(1);
format.setSampleSize(8);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
// get default input device,
QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
if(!info.isFormatSupported(format))
{
format = info.nearestFormat(format);
}
QTimer::singleShot(10000, this, SLOT(slot_stopRecording()));
m_audioInput = new QAudioInput(format, this);
m_audioInput->start(&m_file);
m_labelTips->setText(tr("recording..."));
}
停止录制函数:
void MainWindow::slot_stopRecording()
{
m_btnPlay->setDisabled(false);
m_btnRecord->setDisabled(false);
m_audioInput->stop();
m_labelTips->setText(tr("stop recorded!"));
m_file.close();
delete m_audioInput;
}
//开始播放
void MainWindow::slot_startPlay()
{
m_btnPlay->setDisabled(true);
m_btnRecord->setDisabled(true);
m_file.setFileName("test.raw");
m_file.open(QIODevice::ReadOnly);
QAudioFormat format;
format.setFrequency(8000);
format.setChannels(1);
format.setSampleSize(8);
format.setCodec("aduio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
if(!info.isFormatSupported(format))
// return;
m_audioOutput = new QAudioOutput(format, this);
connect(m_audioOutput, SIGNAL(stateChanged(QAudio::State)), SLOT(slot_finishedPlaying(QAudio::State)));
m_audioOutput->start(&m_file);
m_labelTips->setText(tr("playing..."));
}
// 完成播放
void MainWindow::slot_finishedPlaying(QAudio::State state)
{
if(state == QAudio::IdleState)
{
m_btnPlay->setDisabled(false);
m_btnRecord->setDisabled(false);
m_audioOutput->stop();
m_labelTips->setText(tr("play stop!"));
m_file.close();
delete m_audioOutput;
}
}