3

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();
Akapulka
  • 63
  • 6
  • You take the content of file.wav and try to pass it as source URL (!) of the QSoundEffect, which is wrong. You need to pass the path (e.g. QUrl::fromLocalFile(“file:///path/to/your/file.wav”)) instead. – Frank Osterfeld Oct 18 '15 at 12:34

1 Answers1

1

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();
}
Tarod
  • 6,732
  • 5
  • 44
  • 50
  • 1
    Where are you setting the QSoundEffect's parent? I don't see it passed in anywhere. – Max Strater Mar 26 '19 at 08:44
  • 1
    This is now a long time past, but there is a QSoundEffect method called "setParent", I don't see that getting called in the code above, but it's in the version of Qt I'm using. – Robert McLean Jun 01 '23 at 21:09