gpt4 book ai didi

c++ - 在 C++ 和 QT 中播放 wav 音频文件

转载 作者:行者123 更新时间:2023-11-30 02:59:28 24 4
gpt4 key购买 nike

我正在用 C 读取一个 .wav 文件,然后我尝试使用一些 QT 函数播放音频文件。这是我读取文件的方式:

FILE *fhandle=fopen("myAudioFile.wav","rb");
fread(ChunkID,1,4,fhandle);
fread(&ChunkSize,4,1,fhandle);
fread(Format,1,4,fhandle);
fread(Subchunk1ID,1,4,fhandle);
fread(&Subchunk1Size,4,1,fhandle);
fread(&AudioFormat,2,1,fhandle);
fread(&NumChannels,2,1,fhandle);
fread(&SampleRate,4,1,fhandle);
fread(&ByteRate,4,1,fhandle);
fread(&BlockAlign,2,1,fhandle);
fread(&BitsPerSample,2,1,fhandle);
fread(&Subchunk2ID,1,4,fhandle);
fread(&Subchunk2Size,4,1,fhandle);
Data=new quint16 [Subchunk2Size/(BitsPerSample/8)];
fread(Data,BitsPerSample/8,Subchunk2Size/(BitsPerSample/8),fhandle);
fclose(fhandle);

所以我的音频文件在 Data 中。 Data 的每个元素都是无符号的 16 位整数。

为了播放声音,我将每个 16 位无符号整数分成两个字符,然后每 3 毫秒(使用计时器)向声卡发送 256 个字符。假设 myData 是一个包含 256 个字符的字符数组,我这样做(每 3 毫秒)来播放声音:

m_output->write(myData, 256);

此外,m_output 定义为:

m_output = m_audioOutput->start();

m_audioOutput定义为:

m_audioOutput = new QAudioOutput(m_Outputdevice, m_format, this); 

音频格式正确设置为:

m_format.setFrequency(44100); 
m_format.setChannels(2);
m_format.setSampleSize(16);
m_format.setSampleType(QAudioFormat::UnSignedInt );
m_format.setByteOrder(QAudioFormat::LittleEndian);
m_format.setCodec("audio/pcm");

但是,当我尝试运行代码时,我听到了一些与真实音频文件截然不同的噪音。我做错了什么吗?

谢谢,田杰

最佳答案

我认为问题在于您使用的是 QTimer。 QTimer 绝对不允许您精确地每三毫秒运行一次代码,无论您使用的是什么平台。如果你只差一个样本,你的音频就会听起来很糟糕。根据QTimer docs :

...they are not guaranteed to time out at the exact value specified. In many situations, they may time out late by a period of time that depends on the accuracy of the system timers.

...the accuracy of the timer will not equal [1 ms] in many real-world situations.

尽管我很喜欢 Qt,但我不会尝试将它用于信号处理。我会使用另一个框架,例如 JUCE .

关于c++ - 在 C++ 和 QT 中播放 wav 音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12886272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com