qt实现录音功能



//初始化录音
void Player::InitRecording()
{


    //设置录音格式  8000hz\单声道\8bit\unsigned int数据\小段排列
//    ui->LbProgress->setText(tr("00:00/00:00"));
    QAudioFormat format;
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::UnSignedInt);


    //设置输入设备配置信息
    QAudioDeviceInfo m_InputDeviceInfo = QAudioDeviceInfo::defaultInputDevice();
    if(!m_InputDeviceInfo.isFormatSupported(format))
    {
        format = m_InputDeviceInfo.nearestFormat(format);
    }
    m_pQAudioInput = new QAudioInput(m_InputDeviceInfo,format,this);




    //获取输出设备配置信息
    QAudioDeviceInfo dev = QAudioDeviceInfo::defaultOutputDevice();
    if(!dev.isFormatSupported(format))
    {
        format = dev.nearestFormat(format);
    }
    m_pQAudioOutput = new QAudioOutput(format);
    m_pOutputDevice = new QVideoIODevice();




    //线程实现
     m_pAudioThread = new QThread(this);
     m_pQAudioInput->moveToThread(m_pAudioThread);


     connect( m_pAudioThread,SIGNAL( started() ),this,SLOT( SlotStartRecording() ) );
     connect( m_pAudioThread,SIGNAL( finished() ),this,SLOT( SlotStopRecording() ) );

}

//录音按钮
 
  
void Player::on_BtnRecoreding_clicked()
{
    if( m_pAudioThread->isRunning() )
        m_pAudioThread->quit();
    else
        m_pAudioThread->start();
 
  
}
//开始录音
void Player::SlotStartRecording()
{
    m_pInputIODevice = m_pQAudioInput->start();
    connect(m_pInputIODevice,SIGNAL(readyRead()),this,SLOT(slotReadVoice()));
    m_pQAudioOutput->start(m_pOutputDevice);
 
  
    ui->BtnRecoreding->setText(tr("停止"));
}
//停止录音
void Player::SlotStopRecording()
{
    m_pQAudioInput->stop();
    m_pQAudioOutput->stop();
    disconnect(m_pInputIODevice,SIGNAL(readyRead()),this,SLOT(slotReadVoice()));
    ui->BtnRecoreding->setText(tr("录音"));
}
 
  
void Player::slotReadVoice()
{
    m_pOutputDevice->write(m_pInputIODevice->readAll());
}


你可能感兴趣的:(qt实现录音功能)