qt 怎么用QDataStream读取wav文件最后800个数据并
时间: 2023-06-09 09:04:57 浏览: 82
QT实现wav音频文件读写
转化成float类型?
你可以通过以下的代码来实现:
```c++
#include <QDataStream>
#include <QFile>
QFile file("audio.wav");
if (!file.open(QIODevice::ReadOnly)) {
qWarning() << "Failed to open file!";
return;
}
QDataStream stream(&file);
stream.setByteOrder(QDataStream::LittleEndian); // WAV文件采用小端字节序
// 读取WAV文件头
char riff[4] = {'\0'};
quint32 fileSize = 0;
char wave[4] = {'\0'};
char fmt[4] = {'\0'};
quint32 fmtSize = 0;
quint16 audioFormat = 0;
quint16 numChannels = 0;
quint32 sampleRate = 0;
quint32 byteRate = 0;
quint16 blockAlign = 0;
quint16 bitsPerSample = 0;
while (!stream.atEnd()) {
stream.readRawData(riff, 4);
stream >> fileSize;
stream.readRawData(wave, 4);
stream.readRawData(fmt, 4);
stream >> fmtSize;
stream >> audioFormat;
stream >> numChannels;
stream >> sampleRate;
stream >> byteRate;
stream >> blockAlign;
stream >> bitsPerSample;
if (memcmp(riff, "RIFF", 4) == 0 &&
memcmp(wave, "WAVE", 4) == 0 &&
memcmp(fmt, "fmt ", 4) == 0) {
// 找到WAV文件头
break;
}
}
// 跳过不需要的数据块
while (!stream.atEnd()) {
char data[4] = {'\0'};
quint32 dataSize = 0;
stream.readRawData(data, 4);
stream >> dataSize;
if (memcmp(data, "data", 4) == 0) {
// 找到数据块
break;
} else {
stream.skipRawData(dataSize);
}
}
// 读取最后800个16位的数据,并转换成float类型
const int numSamples = 800;
qint16 data[numSamples] = {0};
for (int i = 0; i < numSamples; i++) {
stream >> data[i];
}
float floatData[numSamples] = {0};
for (int i = 0; i < numSamples; i++) {
floatData[i] = static_cast<float>(data[i]) / static_cast<float>(32768);
}
file.close();
```
上述代码首先打开WAV文件,然后依次读取WAV文件头和数据块,并找到最后800个数据。这里假设WAV文件采用的是16位带符号整数采样,所以读取到的数据需要处理成float类型,范围在[-1.0, 1.0]之间。如果WAV文件采用的是其他的采样格式,需要相应地修改代码。
阅读全文