Home > Software design >  how to add sound to a game in qt in an interface
how to add sound to a game in qt in an interface

Time:01-09

i want to add a music in my game for a school project in qt but i saw that we have to use setMedia but he don't recognize it in the QMediaPLayer class and video about it are from so 2015 i think it change and i put a setSource but nos sound is coming from my game. I tried this but i don't have any ideas to make it work. Please help me.

#include <QMediaPlayer>

 QMediaPlayer * player = new QMediaPlayer();
    player->setSource(QUrl::fromLocalFile("C:/Users/Lea_CHABBAL/OneDrive/Bureau"));
    player->play();

CodePudding user response:

So that an audio file can be output, you must also set the output of your media player. It is also important to make an entry in your project file:

qmake : QT = core gui multimedia (add multimedia)

The code could then look like this:

#include <QMediaPlayer>
#include <QAudioOutput>

........
// if you want to use it as SLOT, it will be make sense to 
// declare the mediaplayer and output in a header file

QMediaPlayer *player = new QMediaPlayer;
QAudioOutput *output = new QAudioOutput;

player->setAudioOutput(output);
player->setSource(QUrl("path"));

output->setVolume(0.5); // <--- floating numbers. from 0 - 1

player->play();

........

CodePudding user response:

Try this (and don't forget the filename.wav at the end of the path)

    musicPlayer = new QMediaPlayer(this);
    musicPlayer->setVolume(30);
    musicPlayer->setSource(QUrl::fromLocalFile("C:/Users/Lea_CHABBAL/OneDrive/Bureau/daftpunk_compil.wav"));
    if(musicPlayer->error() == QMediaPlayer::NoError)
        musicPlayer->play();
    else
        qDebug()<<musicPlayer->errorString();

  • Related