Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Audio not playing from .qrc resources
Forum Updated to NodeBB v4.3 + New Features

Audio not playing from .qrc resources

Scheduled Pinned Locked Moved Solved General and Desktop
20 Posts 6 Posters 4.8k Views 3 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • sierdzioS Offline
    sierdzioS Offline
    sierdzio
    Moderators
    wrote on last edited by
    #2

    With QRC, it's always a bit tricky, but I think it should work. Some things to try:

    • verify that file exists in QRC with QFile / QFileInfo
    • try "qrc://music/sound.mp3" and "qrc:/music/sound.mp3"
    • do not use QUrl::fromLocalFile but a regular QUrl constructor player->setMedia(QUrl("qrc:/music/sound.mp3"));

    (Z(:^

    1 Reply Last reply
    8
    • nageshN Offline
      nageshN Offline
      nagesh
      wrote on last edited by
      #3

      @Xena_o
      As per qt doc.. If you want to know what error happened while loading media..

      Listen for the mediaStatusChanged() and error() signals to be notified when the media is loaded and when an error occurs during loading.
      

      https://doc.qt.io/qt-5/qmediaplayer.html#setMedia

      1 Reply Last reply
      3
      • Xena_oX Offline
        Xena_oX Offline
        Xena_o
        wrote on last edited by
        #4

        @sierdzio i tried all your variants and some more based on your variants, none of them work unfortunatly

        @nagesh error() returns : QMediaPlayer::NoError and mediaStatus() returns QMediaPlayer::LoadingMedia

        kshegunovK 1 Reply Last reply
        0
        • sierdzioS Offline
          sierdzioS Offline
          sierdzio
          Moderators
          wrote on last edited by
          #5

          In that case, you should be able to get it working by opening the MP3 with QFile and passing it as second argument to setMedia() https://doc.qt.io/qt-5/qmediaplayer.html#setMedia:

          QFile file("qrc://music/sound.mp3");
          if (file.open(QFile::Read)) {
            player->setMedia("qrc://music/sound.mp3", &file);
          } else {
            qDebug() << "Oops!";
          }
          

          (Z(:^

          1 Reply Last reply
          3
          • Xena_oX Xena_o

            @sierdzio i tried all your variants and some more based on your variants, none of them work unfortunatly

            @nagesh error() returns : QMediaPlayer::NoError and mediaStatus() returns QMediaPlayer::LoadingMedia

            kshegunovK Offline
            kshegunovK Offline
            kshegunov
            Moderators
            wrote on last edited by kshegunov
            #6

            Is the resource loaded at runtime or compiled into the binary? You should make sure the file's available for reading, like @sierdzio suggested.

            Read and abide by the Qt Code of Conduct

            1 Reply Last reply
            0
            • Xena_oX Offline
              Xena_oX Offline
              Xena_o
              wrote on last edited by Xena_o
              #7

              screenshot

              for some reasons this code is not fine, i added #include <QFile>

              seems cannot use audio from resources

              @kshegunov it is available for reading, the test of opening it from local directory works well, seems just from resources it wont open

              kshegunovK 1 Reply Last reply
              0
              • Xena_oX Xena_o

                screenshot

                for some reasons this code is not fine, i added #include <QFile>

                seems cannot use audio from resources

                @kshegunov it is available for reading, the test of opening it from local directory works well, seems just from resources it wont open

                kshegunovK Offline
                kshegunovK Offline
                kshegunov
                Moderators
                wrote on last edited by kshegunov
                #8

                @Xena_o said in Audio not playing from .qrc resources:

                for some reasons this code is not fine, i added #include <QFile>

                Yet didn't check the QMediaPlayer::setMedia documentation - the inline annotations already tell you something's wrong on that row. The QMediaContent object has an implicit constructor from QUrl that's why you can use QUrl directly. Try something like:

                QFile file(":/music/sound.mp3"); //< QFile doesn't know about protocols
                if (file.open(QFile::Read))
                  player->setMedia(QMediaContent(nullptr), &file);
                else
                  qDebug() << "Oops!";
                

                @kshegunov it is available for reading, the test of opening it from local directory works well, seems just from resources it wont open

                Available for reading from the resource! Also please answer the question as well.

                Read and abide by the Qt Code of Conduct

                Xena_oX 1 Reply Last reply
                1
                • kshegunovK kshegunov

                  @Xena_o said in Audio not playing from .qrc resources:

                  for some reasons this code is not fine, i added #include <QFile>

                  Yet didn't check the QMediaPlayer::setMedia documentation - the inline annotations already tell you something's wrong on that row. The QMediaContent object has an implicit constructor from QUrl that's why you can use QUrl directly. Try something like:

                  QFile file(":/music/sound.mp3"); //< QFile doesn't know about protocols
                  if (file.open(QFile::Read))
                    player->setMedia(QMediaContent(nullptr), &file);
                  else
                    qDebug() << "Oops!";
                  

                  @kshegunov it is available for reading, the test of opening it from local directory works well, seems just from resources it wont open

                  Available for reading from the resource! Also please answer the question as well.

                  Xena_oX Offline
                  Xena_oX Offline
                  Xena_o
                  wrote on last edited by Xena_o
                  #9

                  @kshegunov here is final code

                  QFile file(":/music/music/sound.mp3");
                      if (file.open(QIODevice::ReadOnly)) {
                        player->setMedia(QMediaContent(nullptr), &file);
                      } else {
                        qDebug() << "Oops!";
                      }
                  

                  the accepted code is : QIODevice::ReadOnly and not QFile::Read
                  the file is in resources.qrc, i dont know how to figure if it is available

                  the ouptput: no oops, and QMediaPlayer::NoError QMediaPlayer::LoadingMedia

                  but still the sound is not playing. so far if i well understand, it is loading it, but thats it, not playing

                  player->setVolume(50);
                      player->play();
                  

                  this is doing nothing

                  kshegunovK 1 Reply Last reply
                  0
                  • Xena_oX Xena_o

                    @kshegunov here is final code

                    QFile file(":/music/music/sound.mp3");
                        if (file.open(QIODevice::ReadOnly)) {
                          player->setMedia(QMediaContent(nullptr), &file);
                        } else {
                          qDebug() << "Oops!";
                        }
                    

                    the accepted code is : QIODevice::ReadOnly and not QFile::Read
                    the file is in resources.qrc, i dont know how to figure if it is available

                    the ouptput: no oops, and QMediaPlayer::NoError QMediaPlayer::LoadingMedia

                    but still the sound is not playing. so far if i well understand, it is loading it, but thats it, not playing

                    player->setVolume(50);
                        player->play();
                    

                    this is doing nothing

                    kshegunovK Offline
                    kshegunovK Offline
                    kshegunov
                    Moderators
                    wrote on last edited by
                    #10

                    @Xena_o said in Audio not playing from .qrc resources:

                    the accepted code is : QIODevice::ReadOnly and not QFile::Read

                    Yes, I don't compile example code before I post it, so there may be minor errors.

                    What does this output, have you checked the signals that are raised?

                    QObject::connect(player, &QMediaPlayer::bufferStatusChanged, this, [this] (int percent) -> void  {
                        qDebug() << "QMediaPlayer::bufferStatusChanged" << percent;
                    });
                    QObject::connect(player, &QMediaPlayer::durationChanged, this, [this] (qint64 duration) -> void  {
                        qDebug() << "QMediaPlayer::durationChanged" << duration;
                    });
                    QObject::connect(player, &QMediaPlayer::error, this, [this] (QMediaPlayer::Error code) -> void  {
                        qDebug() << "QMediaPlayer::Error" << code;
                    });
                    QObject::connect(player, &QMediaPlayer::mediaStatusChanged, this, [this] (QMediaPlayer::MediaStatus status) -> void  {
                        qDebug() << "QMediaPlayer::mediaStatusChanged" << status;
                    });
                    QObject::connect(player, &QMediaPlayer::stateChanged, this, [this] (QMediaPlayer::State state) -> void  {
                        qDebug() << "QMediaPlayer::stateChanged" << state;
                    });
                    
                    QFile file(":/music/music/sound.mp3");
                    if (file.open(QIODevice::ReadOnly)) {
                        player->setMedia(QMediaContent(nullptr), &file);
                    } else {
                        qDebug() << "Oops!";
                    }
                    player->setVolume(50);
                    player->play();
                    

                    Read and abide by the Qt Code of Conduct

                    1 Reply Last reply
                    0
                    • Xena_oX Offline
                      Xena_oX Offline
                      Xena_o
                      wrote on last edited by
                      #11

                      @kshegunov alright it is saying the media is invalid :

                      QMediaPlayer::mediaStatusChanged QMediaPlayer::LoadingMedia
                      QMediaPlayer::stateChanged QMediaPlayer::PlayingState
                      QMediaPlayer::mediaStatusChanged QMediaPlayer::InvalidMedia

                      but that is not true, it is an mp3 file, and it is reading from local directory, so why is it invalid from Resources ?!

                      kshegunovK 1 Reply Last reply
                      0
                      • Xena_oX Xena_o

                        @kshegunov alright it is saying the media is invalid :

                        QMediaPlayer::mediaStatusChanged QMediaPlayer::LoadingMedia
                        QMediaPlayer::stateChanged QMediaPlayer::PlayingState
                        QMediaPlayer::mediaStatusChanged QMediaPlayer::InvalidMedia

                        but that is not true, it is an mp3 file, and it is reading from local directory, so why is it invalid from Resources ?!

                        kshegunovK Offline
                        kshegunovK Offline
                        kshegunov
                        Moderators
                        wrote on last edited by
                        #12

                        As I said make absolutely certain that the file can be read.

                        const QString filePath(":/music/sound.mp3")
                        Q_ASSERT(QFile::exists(filePath));
                        ...
                        QFile file(filePath);
                        if (file.open(QIODevice::ReadOnly)) {
                           ...
                        

                        Read and abide by the Qt Code of Conduct

                        1 Reply Last reply
                        0
                        • Xena_oX Offline
                          Xena_oX Offline
                          Xena_o
                          wrote on last edited by Xena_o
                          #13

                          @kshegunov Q_ASSERT(QFile::exists(filePath)); is not outputing anything and app is not crashing, so this means the file is available right? but still it is an invalid media, i tried to convert to .wav but still it is an invalid media !

                          1 Reply Last reply
                          0
                          • Xena_oX Offline
                            Xena_oX Offline
                            Xena_o
                            wrote on last edited by Xena_o
                            #14

                            i saw a post where people are copying the audio file from the resources file to a temporary local directory, then playing it from the local directory, then deleting it.

                            This means it is not possible to play audio from resources, its kind of insane, isnt it ?

                            Pl45m4P 1 Reply Last reply
                            0
                            • Xena_oX Offline
                              Xena_oX Offline
                              Xena_o
                              wrote on last edited by
                              #15
                              const QString filePath(":/music/music/sound.mp3");
                                  Q_ASSERT(QFile::exists(filePath));
                              
                                  QFile file2(QDir::tempPath() + "/temp0.mp3");
                              
                                  if (file2.open(QIODevice::ReadWrite))
                                  {
                                      QFile workFile(filePath);
                                      if(workFile.open(QIODevice::ReadOnly))
                                      {
                                        file2.write(workFile.readAll());
                                        workFile.close();
                                      }
                              
                                      file2.close();
                                  }
                                  player->setMedia(QUrl::fromLocalFile((QDir::tempPath() + "/temp0.mp3")));
                                  player->setVolume(50);
                                  player->play();
                              

                              this code is working, but its too bad i need to copy from resources to temporary file to be able to play the audio, that is bad...

                              1 Reply Last reply
                              0
                              • Xena_oX Xena_o

                                i saw a post where people are copying the audio file from the resources file to a temporary local directory, then playing it from the local directory, then deleting it.

                                This means it is not possible to play audio from resources, its kind of insane, isnt it ?

                                Pl45m4P Offline
                                Pl45m4P Offline
                                Pl45m4
                                wrote on last edited by Pl45m4
                                #16

                                @Xena_o said in Audio not playing from .qrc resources:

                                This means it is not possible to play audio from resources, its kind of insane, isnt it ?

                                I don't think that it's not possible.
                                Have you tried it using QSound instead of QMediaPlayer?

                                @aha_1980 said that it worked:

                                • https://forum.qt.io/topic/88581/how-to-play-a-wav-file-that-is-defined-in-resource-file/8

                                How does your resource file look like?


                                If debugging is the process of removing software bugs, then programming must be the process of putting them in.

                                ~E. W. Dijkstra

                                Xena_oX 1 Reply Last reply
                                1
                                • Pl45m4P Pl45m4

                                  @Xena_o said in Audio not playing from .qrc resources:

                                  This means it is not possible to play audio from resources, its kind of insane, isnt it ?

                                  I don't think that it's not possible.
                                  Have you tried it using QSound instead of QMediaPlayer?

                                  @aha_1980 said that it worked:

                                  • https://forum.qt.io/topic/88581/how-to-play-a-wav-file-that-is-defined-in-resource-file/8

                                  How does your resource file look like?

                                  Xena_oX Offline
                                  Xena_oX Offline
                                  Xena_o
                                  wrote on last edited by Xena_o
                                  #17

                                  @Pl45m4 wow i get a progress with this !

                                  QSound::play(":/music/music/sound.mp3"); throws
                                  QSoundEffect(qaudio): Error decoding source file::/music/music/sound.mp3

                                  but

                                  QSound::play(":/music/music/sound.wav"); (i converted the file) this one is WORKING !

                                  too bad it doesnt handle mp3 or maybe i need add extra params, will look it.

                                  edit: seems QSound do not support mp3, too bad, well wav is better than nothing

                                  thanks to everybody for participation and help :-)

                                  1 Reply Last reply
                                  2
                                  • nageshN Offline
                                    nageshN Offline
                                    nagesh
                                    wrote on last edited by nagesh
                                    #18

                                    @Xena_o I have checked by adding .mp3 files to resource in QT musicplayer example,
                                    and it's working perfectly fine.

                                    I have accessed the url using

                                    QUrl url = QUrl("qrc:///music/sound.mp3");
                                     player->setMedia(url);
                                    player->play();
                                    

                                    looks like there is no need to copy into temp file.

                                    Got hint from Qt Doc for resources
                                    https://doc.qt.io/qt-5/resources.html

                                    For example, the file path :/images/cut.png or the URL qrc:///images/cut.png would give 
                                    access to the cut.png file, whose location in the application's source tree 
                                    is images/cut.png.
                                    
                                    Xena_oX 1 Reply Last reply
                                    4
                                    • nageshN nagesh

                                      @Xena_o I have checked by adding .mp3 files to resource in QT musicplayer example,
                                      and it's working perfectly fine.

                                      I have accessed the url using

                                      QUrl url = QUrl("qrc:///music/sound.mp3");
                                       player->setMedia(url);
                                      player->play();
                                      

                                      looks like there is no need to copy into temp file.

                                      Got hint from Qt Doc for resources
                                      https://doc.qt.io/qt-5/resources.html

                                      For example, the file path :/images/cut.png or the URL qrc:///images/cut.png would give 
                                      access to the cut.png file, whose location in the application's source tree 
                                      is images/cut.png.
                                      
                                      Xena_oX Offline
                                      Xena_oX Offline
                                      Xena_o
                                      wrote on last edited by
                                      #19

                                      @nagesh wonderful ! thank you ! i tested it is working. AMediaPlayer offers more control than QSound.

                                      1 Reply Last reply
                                      0
                                      • 8Observer88 Offline
                                        8Observer88 Offline
                                        8Observer8
                                        wrote on last edited by 8Observer8
                                        #20

                                        My example works with Qt 6.2.4. You can download it from DropBox here. Many thanks to the guys in this topic: How to play sounds using QMediaPlayer

                                        media-player-qt6-cpp.pro

                                        QT       += core gui multimedia
                                        
                                        greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
                                        
                                        CONFIG += c++17
                                        
                                        # You can make your code fail to compile if it uses deprecated APIs.
                                        # In order to do so, uncomment the following line.
                                        #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
                                        
                                        SOURCES += \
                                            main.cpp \
                                            widget.cpp
                                        
                                        HEADERS += \
                                            widget.h
                                        
                                        # Default rules for deployment.
                                        qnx: target.path = /tmp/$${TARGET}/bin
                                        else: unix:!android: target.path = /opt/$${TARGET}/bin
                                        !isEmpty(target.path): INSTALLS += target
                                        
                                        RESOURCES += \
                                            audio.qrc
                                        

                                        widget.h

                                        #ifndef WIDGET_H
                                        #define WIDGET_H
                                        
                                        #include <QtWidgets/QWidget>
                                        #include <QtMultimedia/QMediaPlayer>
                                        
                                        class Widget : public QWidget
                                        {
                                            Q_OBJECT
                                        
                                        public:
                                            Widget(QWidget *parent = nullptr);
                                            ~Widget();
                                        
                                        private slots:
                                            void play();
                                        
                                        private:
                                            QMediaPlayer mediaPlayer;
                                        };
                                        #endif // WIDGET_H
                                        

                                        widget.cpp

                                        #include "widget.h"
                                        #include <QtCore/QUrl>
                                        #include <QtWidgets/QPushButton>
                                        #include <QtMultimedia/QAudioOutput>
                                        
                                        Widget::Widget(QWidget *parent)
                                            : QWidget(parent)
                                        {
                                            mediaPlayer.setSource(QUrl("qrc:/assets/audio/music.wav"));
                                            mediaPlayer.setAudioOutput(new QAudioOutput);
                                        
                                            QPushButton *playButton = new QPushButton("Play", this);
                                            connect(playButton, &QPushButton::pressed, this, &Widget::play);
                                        
                                            connect(&mediaPlayer, &QMediaPlayer::mediaStatusChanged,
                                                    [=](QMediaPlayer::MediaStatus status) -> void{ qDebug() << "QMediaPlayer::mediaStatusChanged" << status;}
                                            );
                                        }
                                        
                                        Widget::~Widget()
                                        {
                                        }
                                        
                                        void Widget::play()
                                        {
                                            mediaPlayer.play();
                                            qDebug() << "play";
                                        }
                                        

                                        main.cpp

                                        #include "widget.h"
                                        
                                        #include <QApplication>
                                        
                                        int main(int argc, char *argv[])
                                        {
                                            QApplication a(argc, argv);
                                            Widget w;
                                            w.show();
                                            return a.exec();
                                        }
                                        
                                        1 Reply Last reply
                                        0
                                        • JonBJ JonB referenced this topic on

                                        • Login

                                        • Login or register to search.
                                        • First post
                                          Last post
                                        0
                                        • Categories
                                        • Recent
                                        • Tags
                                        • Popular
                                        • Users
                                        • Groups
                                        • Search
                                        • Get Qt Extensions
                                        • Unsolved