I don't know if it's a bug or it's just a lack of information in the documentation, but the fact is that you need to set a parent for your QSoundEffect
.
For example, if you put your code in the main
function, it won't work, as I suppose you already checked.
However, if you write the following code, where the QSoundEffect
object has a QWidget
as parent, you will hear the sound correctly.
(I uploaded the complete example to GitHub)
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget q;
q.show();
q.play();
return a.exec();
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSoundEffect>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
void play();
private:
QSoundEffect effect;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent), effect(this)
{
effect.setSource(QUrl::fromLocalFile(":res/kid_giggle.wav"));
effect.setLoopCount(QSoundEffect::Infinite);
effect.setVolume(1.00f);
}
Widget::~Widget()
{
}
void Widget::play()
{
effect.play();
}