QSoundEffect always loading status in Qt 5.4

1.2k views Asked by At

Following code isn't working. QSoundEffect::status always return QSoundEffect::Loading and QSoundEffect::isLoaded return false.

QFile file("file.wav");
file.open(QIODevice::ReadWrite);
QByteArray data = file.readAll();
file.close();

QSoundEffect sound;
sound.setSource(QUrl::fromEncoded(data));
sound.setVolume(1.0f);
sound.play();
1

There are 1 answers

2
Tarod On

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();
}