qt实现pcm音频播放
方法一
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QAudioFormat>
#include <QAudioOutput>
#include <QDebug>
#pragma execution_character_set("utf-8")
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("./out.pcm");
if (file.open(QIODevice::ReadOnly))
{
qDebug() << "打开成功!";
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
qDebug() << info.supportedSampleTypes();
qDebug() << info.supportedByteOrders();
qDebug() << info.supportedCodecs();
qDebug() << info.supportedSampleRates();
QAudioFormat fmt;
fmt.setSampleRate(44100);
fmt.setSampleSize(16);
fmt.setChannelCount(2);
fmt.setCodec("audio/pcm");
fmt.setByteOrder(QAudioFormat::LittleEndian);
fmt.setSampleType(QAudioFormat::UnSignedInt);
if (!info.isFormatSupported(fmt))
{
qDebug() << "输出设备不支持该格式,不能播放音频";
return 0;
}
QAudioOutput* audio = new QAudioOutput(fmt, qApp);
audio->start(&file);
delete audio;
audio = nullptr;
}
return a.exec();
}
方法二
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QAudioFormat>
#include <QAudioOutput>
#include <QDebug>
#include <QThread>
#pragma execution_character_set("utf-8")
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("./out.pcm");
if (file.open(QIODevice::ReadOnly))
{
qDebug() << "打开成功!";
QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
qDebug() << info.supportedSampleTypes();
qDebug() << info.supportedByteOrders();
qDebug() << info.supportedCodecs();
qDebug() << info.supportedSampleRates();
QAudioFormat fmt;
fmt.setSampleRate(44100);
fmt.setSampleSize(16);
fmt.setChannelCount(2);
fmt.setCodec("audio/pcm");
fmt.setByteOrder(QAudioFormat::LittleEndian);
fmt.setSampleType(QAudioFormat::UnSignedInt);
if (!info.isFormatSupported(fmt))
{
qDebug() << "输出设备不支持该格式,不能播放音频";
return 0;
}
QAudioOutput* audio = new QAudioOutput(fmt, qApp);
QIODevice* io = audio->start();
int size = audio->periodSize();
QByteArray buf = file.readAll();
file.close();
while (!buf.isEmpty())
{
if (audio->bytesFree() < size)
{
QThread::msleep(1);
continue;
}
io->write(buf.mid(0, size));
buf.remove(0, size);
qDebug() << buf.count();
}
io->close();
delete io;
io = nullptr;
}
return a.exec();
}