非常抱歉,之前给出的代码有误。你提供的代码是使用 QSoundEffect
来播放音频文件,并设置音量的方式是正确的。
以下是修正后的代码:
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QFileDialog>
#include <QSoundEffect>
class MainWindow : public QWidget {
public:
MainWindow(QWidget *parent = nullptr) : QWidget(parent) {
QPushButton *button = new QPushButton("Open File", this);
connect(button, &QPushButton::clicked, this, &MainWindow::openFile);
}
private slots:
void openFile() {
QString filePath = QFileDialog::getOpenFileName(this, "Select WAV File", "", "WAV Files (*.wav)");
if (!filePath.isEmpty()) {
playAudio(filePath);
}
}
void playAudio(const QString& filePath) {
QSoundEffect *effect = new QSoundEffect;
effect->setSource(QUrl::fromLocalFile(filePath));
effect->setVolume(0.5); // 设置音量,范围为0-1
effect->play();
}
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
这个示例中通过点击 “Open File” 按钮选择要播放的 WAV 文件,并使用 QSoundEffect
类来实现音频的播放功能。同时可以使用 setVolume()
函数设置音量,其取值范围是 0-1。
内容由零声教学AI助手提供,问题来源于学员提问