【问题标题】:Play Sound File with C++ and Qt 5使用 C++ 和 Qt 5 播放声音文件
【发布时间】:2017-07-31 23:50:58
【问题描述】:

如何使用 Qt 5 和 C++ 播放声音文件?我试过QSound,但我被告知它在Ubuntu(我当前的操作系统)中不起作用,我听说过Phonon,但我的Qt包中似乎没有该库。

【问题讨论】:

  • 是什么让你觉得 QSound 不能在 Ubuntu 上运行?
  • 当我尝试它时,它不起作用,在查看了一些关于它的信息后,它的功能是知道它是否适用于我的系统,我得到了一个错误的响应。
  • 你要么需要让 Qt 的多媒体 API 工作,在这种情况下你可以使用 QSound 或 QAudioOutput 或类似的,或者找到一些非基于 Qt 的 API 来播放声音。如果您的程序是基于 Qt 的应用程序,那么前一种方法会更可取。
  • 我没有遇到这个,但我似乎没有“Qt Multimedia”库,我在 repos 中找不到它。

标签: c++ qt audio


【解决方案1】:

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++

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

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

SND_选项设置为SND_ASYNC

PlaySound reference : MSDN

无论如何你都可以听音频。

【讨论】:

  • PlaySound 不是 Windows 函数吗?我以为 OP 正在使用 Ubuntu。更不用说,Qt代码看起来完全是从Bart's answer to 14296326复制过来的;在 CC BY-SA 3.0 下,您至少应该属性。
【解决方案2】:

安装包含实用程序play 的包sox。或者您可以使用mplayer 或任何控制台媒体播放器。然后使用QProcess开始播放声音文件。

#include <QProcess>

.......

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

.......

【讨论】:

  • 谢谢,这似乎对我有用,但在使用我的“qrc”资源文件中的音频文件时确实会出错。有什么想法吗?
  • @OmariCelestine 据我所知,外部程序(使用 QProcess 启动的程序)无法访问应用程序中的资源。无论如何,我不会将此选项视为最佳选项,因为它不允许与玩家互动,例如暂停、播放等。如果您需要访问资源或想要互动,请考虑 Bryant 的回答与播放器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多