Omari Celestine
Omari Celestine

Reputation: 1435

Play Sound File with C++ and Qt 5

How can I play a sound file using Qt 5 and C++? I have tried QSound but I am told it does not workin Ubuntu (my current Operating System) and I have heard of Phonon but the library does not seem to be available in my Qt Package.

Upvotes: 0

Views: 5069

Answers (2)

Bryant
Bryant

Reputation: 324

Qt5

QFile inputFile;
QAudioOutput* audio;
inputFile.setFileName("/tmp/test.raw");
inputFile.open(QIODevice::ReadOnly);

QAudioFormat format;
// Set up the format, eg.
format.setFrequency(7600);
format.setChannels(1);
format.setSampleSize(6);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);

QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
if (!info.isFormatSupported(format)) {
    qWarning()<<"raw audio format not supported by backend, cannot play audio.";
    return;
}

audio = new QAudioOutput(format, this);

connect(audio,SIGNAL(stateChanged(QAudio::State)),SLOT(finishedPlaying(QAudio::State)));
 audio->start(&inputFile);

C++

Use BOOL PlaySound(LPCTSTR pszSound, HMODULE hmod, DWORD fdwSound);

#pragma comment (lib, "winmm.lib")
...
PlaySound(TEXT("recycle.wav"), NULL, SND_ASYNC);

Set SND_ option asSND_ASYNC.

PlaySound reference : MSDN

Anyway you can listen the audio.

Upvotes: 6

Michael
Michael

Reputation: 5335

Install the package sox that contains the utility play. Or you can use mplayer or any console media player. Then use QProcess to start playing sound file.

#include <QProcess>

.......

QProcess qprocess;
qprocess.startDetached("play",QStringList()<<"wav/alarm-clock-01.wav");

.......

Upvotes: 1

Related Questions