gpt4 book ai didi

c++ - 如何从 Qt 中的资源文件重复/循环播放声音?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:19:55 28 4
gpt4 key购买 nike

有什么简单的方法可以在 Qt 中播放资源文件中的重复/循环声音吗?

对于单一声音播放,我使用它并且效果很好:

QSound::play(":/Sounds/swoop.wav");

(WORKS)

但这不是:

QSound sound(":/Sounds/swoop.wav");
sound.play();

(DOES NOT WORK)

甚至这样:

QSound sound (":/Sounds/swoop.wav");
sound.setLoops(QSound::Infinite);
sound.play();

(DOES NOT WORK)

我想我应该使用 QSoundEffect 类:

QSoundEffect effect;
effect.setSource(":/Sounds/swoop.wav");
effect.setLoopCount(QSoundEffect::Infinite);
effect.setVolume(0.25f);
effect.play();

但是 QSoundEffect 类不适用于我必须使用的资源文件。我试图找到解决 QFile 的方法,但没有成功。我使用 Qt 5.3.1有什么想法吗?

最佳答案

很难从这些有限的代码片段中猜测,但您确定创建的 QSound 生命周期足够长吗? QSound::~QSound 最终调用了 QSound::stop

编辑:

有 3 种使用 QSound 的方式,让我们看看它们的实际应用:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtDebug>
#include <QSound>

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->pushButton,SIGNAL(clicked()), this, SLOT(first()));
connect(ui->pushButton_2,SIGNAL(clicked()), this, SLOT(second()));
connect(ui->pushButton_3,SIGNAL(clicked()), this, SLOT(third()));

}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::first()
{
const QString path = ui->lineEdit->text();
qDebug() << __PRETTY_FUNCTION__ << ": " << path;
QSound sound(path);
sound.play();
}

MainWindow::first 的问题在于,在创建 sound 对象并调用其方法 play 之后,它立即被销毁(它超出了范围)。由于 QSound 是在析构函数中调用的,因此很可能没有机会播放声音的任何部分。

void MainWindow::third()
{
const QString path = ui->lineEdit->text();
qDebug() << __PRETTY_FUNCTION__ << ": " << path;
QSound* sound = new QSound(path);
sound->play();
}

这样你会播放你的声音但是有内存泄漏,所以你需要添加某种形式的内存管理来销毁 sound 对象 after 声音结束玩。如果你转到 QSound 源,你会看到有一个名为 deleteOnComplete 的插槽。 .不幸的是,它是私有(private)的,所以你自己在这里。

void MainWindow::second()
{
const QString path = ui->lineEdit->text();
qDebug() << __PRETTY_FUNCTION__ << ": " << path;
QSound::play(path);
}

最后一种情况是使用静态play函数。这也是最简单的方法。如果您检查它是如何实现的,它会使用我之前提到的那个私有(private)插槽并将其连接到来自私有(private) QSoundEffect 实例数据成员的信号。您可以找到工作示例 here .

因此,如果您想使用 QSound 播放声音,这就是您的选择。如果你想使用QSoundEffect,有很好的exampleQSound::QSound 中如何构造 QSoundEffect 以便它使用资源。

关于c++ - 如何从 Qt 中的资源文件重复/循环播放声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27878615/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com