gpt4 book ai didi

C++ 在后台读取文件

转载 作者:搜寻专家 更新时间:2023-10-31 02:24:20 24 4
gpt4 key购买 nike

我正在实现一个音频播放器应用程序,它预先缓冲一小部分音频数据,并在需要时读取其余数据,例如播放命令到达时。这是一个实时应用程序,播放命令和播放开始之间的延迟几乎为零非常重要。

示例:我的音频流是 10 Mb,我在选择文件时读取其中的一部分并开始创建这样的缓冲区:

// Stuff to do as soon as the file is selected
// Allocate new memory for the current sample

// contains sample length in number of samples
sampleSize = SampleLib.smp.len;

// assume it's a 16-bit audio file, each sample is 2 bytes long
byteSize = sampleSize * sizeof(short);

// Allow 10 extra samples and fill with zeroes
SampleData = new short[sampleSize + 10]();

// PRELOAD_BYTESIZE is set to 65535 bytes
preloadByteSize = byteSize > PRELOAD_BYTESIZE ? PRELOAD_BYTESIZE : byteSize;

// Set pointer in file - WavePointer contains the exact location where the sample data starts in file
fseek(inFile, WavePointer, SEEK_SET);

// read preloadByteSize from inFile into SampleData
fread(SampleData, 1, preloadByteSize, inFile);

此时我的缓冲区 SampleData 仅包含部分音频数据,以便在播放命令到达时立即开始播放。同时,程序应填充缓冲区的其余部分并继续播放,直到音频样本结束而不会中断。

// Stuff to do as soon the playback starts
// Load the rest of the sample data

// If file is already in memory, avoid reading it again
if (preloadByteSize < ByteSize)
{
// Set pointer in file at stample start + preload size
fseek(fpFile, WavePointers + preloadByteSize, SEEK_SET);

// read the remaining bytes from inFile and fill the empty part of the buffer
fread(SampleData + preloadByteSize / sizeof(short), 1, ByteSize - preloadByteSize, inFile);

// remember the number of loaded bytes
preloadByteSize = ByteSize;
}

我希望代码的第二部分在文件播放时在后台执行,但实际上它都是串行处理,所以直到缓冲区的其余部分加载完毕才会开始播放,从而延迟播放.我可以有一个后台线程来加载文件数据而不干扰音频任务吗?我可以使用 OpenMP 执行此操作吗?

最佳答案

您也许可以使用 OpenMP 执行此操作,但这涉及并发性而非并行性,因此我会查看 pthreads 或 C++11 线程:

关于C++ 在后台读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28128242/

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