发布 | 音量控制器
- 2020 年 2 月 24 日
- 筆記
❝可设置/同步扬声器与录音音量。(目前仅支持Windows系统)❞

功能
- 「可设置扬声器/录音音量,开关静音功能」。
部分代码
- 音量控制类
VolumeController
对外接口。
class VolumeController {public: explicit VolumeController(); virtual ~VolumeController(); int getSpeakerVolume(); bool setSpeakerVolume(int volumePercent); bool isSpeakerMuted(); bool setSpeakerMuted(bool mute); int getMicVolume(); bool setMicVolume(int volumePercent); bool isMicMuted(); bool setMicMuted(bool mute); private: IAudioEndpointVolume* getEndpointVolume(bool isSpeaker); private: IAudioEndpointVolume *m_speakerEndpointVolume; IAudioEndpointVolume *m_micEndpointVolume; };
- 绑定音量状态更新的槽函数
onUpdate()
,并设置更新时间为500ms。
connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(onUpdate())); m_updateTimer.start(500);
onUpdate()
槽函数实现。
void onUpdate() { int micVolume = m_volumeController->getMicVolume(); int speakerVolume = m_volumeController->getSpeakerVolume(); ui->horizontalSlider->setValue(micVolume); ui->horizontalSlider_2->setValue(speakerVolume); ui->label_2->setText(QString::fromLocal8Bit("录音音量:(%1%)").arg(micVolume)); ui->label_3->setText(QString::fromLocal8Bit("扬声器音量:(%1%)").arg(speakerVolume)); }
- 通过触发QSlider的槽函数来设置扬声器或录音的音量,并会将设置结果输出。
void on_horizontalSlider_valueChanged(int value) { qDebug() << "Set mic volume: " << value << "; Result: " << m_volumeController->setMicVolume(value); } void on_horizontalSlider_2_valueChanged(int value) { qDebug() << "Set speaker voluem: " << value << "; Result: " << m_volumeController->setSpeakerVolume(value); }
- 目前更新音量状态变化是使用定时器查询的方法,后续会使用Windows的事件通知去更新音量显示,这样会高效点。