Using a resource file in QMediaPlayer

2019-05-18 17:24发布

问题:

How do I load a .mp3 file to use in a QMediaPlayer from a .qrc resource file?

This is what I have so far

QMediaPlayer *player = new QMediaPlayer;
player->setMedia(QUrl::fromLocalFile(":/audio/theme.mp3"));
player->play();

resources.qrc:

<RCC>
    <qresource prefix="/audio">
        <file>theme.mp3</file>
    </qresource>
</RCC>

theme.mp3 is located in the project directory.

回答1:

Use m_player->setMedia(QUrl("qrc:/audio/theme.mp3"));

If you are using Qt Creator, you can copy this url to clipboard by pressing right button on the audio file in the side bar and choosing Copy url "...".