废话不多说,直接贴代码,代码只是简单的播放以及获取播放状态。
一: 在pro里面添加
QT += multimedia
二:头文件
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtMultimedia/QSoundEffect>
#include <QDir>
#include <QDebug>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void OnPlayingChanged();
private:
void OnPlayVoice(QString fileName);
bool GetPlayState();
private:
QSoundEffect* m_pSoundEffect;//语音播放控件
};
#endif // WIDGET_H
三:函数实现 widget.cpp
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
m_pSoundEffect = new QSoundEffect;//语音播放控件
connect(m_pSoundEffect, SIGNAL(playingChanged()), this, SLOT(OnPlayingChanged()));
QString strFile = "test.wav";
OnPlayVoice(strFile);
}
Widget::~Widget()
{
}
void Widget::OnPlayVoice(QString fileName)//播放wav文件
{
QString strPocPath = QString("%1/%2").arg(QDir::currentPath()).arg(fileName);
m_pSoundEffect->setSource(QUrl::fromLocalFile(strPocPath));
//m_pSoundEffect->setLoopCount(QSoundEffect::Infinite);注释掉只播放一次,打开循环播放
m_pSoundEffect->setVolume(1.0f);
m_pSoundEffect->play();
}
void Widget::OnPlayingChanged()//播放状态改变槽函数
{
bool isPlaying = m_pSoundEffect->isPlaying();
if (!isPlaying)
{
qDebug()<<"not playing";
}
else
{
qDebug()<<"playing";
}
}
bool Widget::GetPlayState()//获取播放状态
{
return m_pSoundEffect->isPlaying();
}
四:将要播放的wav文件拷贝到运行目录下面
五:如果出现类似“QSoundEffect(qaudio): Error decoding source file:xxxx/test.wav”的问题,请检查播放文件路径是否正确。