我正在开发一个播放音频的 Android 应用程序。为了最大限度地减少延迟,我通过 JNI 使用 C++ 来使用 C++ 库双簧管播放应用程序。
目前,在播放之前,应用程序必须解码给定的文件(例如 mp3),然后播放解码后的原始音频流。如果文件较大,这会导致播放开始前的等待时间。所以我想事先进行解码,保存它,当请求播放时,只需播放保存文件中的解码数据。我几乎不知道如何在 C++ 中进行正确的文件 i/o,并且很难理解它。有可能我的问题可以通过正确的库来解决,我不确定。
所以目前我正在像这样保存我的文件:
bool Converter::doConversion(const std::string& fullPath, const std::string& name) {
// here I'm setting up the extractor and necessary inputs. Omitted since not relevant
// this is where the decoder is called to decode a file to raw audio
constexpr int kMaxCompressionRatio{12};
const long maximumDataSizeInBytes = kMaxCompressionRatio * (size) * sizeof(int16_t);
auto decodedData = new uint8_t[maximumDataSizeInBytes];
int64_t bytesDecoded = NDKExtractor::decode(*extractor, decodedData);
auto numSamples = bytesDecoded / sizeof(int16_t);
auto outputBuffer = std::make_unique<float[]>(numSamples);
// This block is necessary to get the correct format for oboe.
// The NDK decoder can only decode to int16, we need to convert to floats
oboe::convertPcm16ToFloat(
reinterpret_cast<int16_t *>(decodedData),
outputBuffer.get(),
bytesDecoded / sizeof(int16_t));
// This is how I currently save my outputBuffer to a file. This produces a file on the disc.
std::string outputSuffix = ".pcm";
std::string outputName = std::string(mFolder) + name + outputSuffix;
std::ofstream outfile(outputName.c_str(), std::ios::out | std::ios::binary);
outfile.write(reinterpret_cast<const char *>(&outputBuffer), sizeof outputBuffer);
return true;
}
所以我相信我拿了我的浮点数组,将它转换为一个字符数组并保存它。我不确定这是否正确,但这是我对它的最佳理解。反正后面有个文件。 编辑:正如我在分析我保存的文件时发现的那样,我只存储了 8 个字节。
现在我如何再次加载这个文件并恢复我的 outputBuffer 的内容?
目前我有这一点,这显然是不完整的:
StorageDataSource *StorageDataSource::openPCM(const char *fileName, AudioProperties targetProperties) {
long bufferSize;
char * buffer;
std::ifstream stream(fileName, std::ios::in | std::ios::binary);
stream.seekg (0, std::ios::beg);
bufferSize = stream.tellg();
buffer = new char [bufferSize];
stream.read(buffer, bufferSize);
stream.close();
如果这是正确的,我该怎么做才能将数据恢复为原始类型?如果我做错了,它如何以正确的方式工作?