打开Ogg Vorbis文件的标准方法是使用ov_fopenov_open。但是,如果文件路径包含非ASCII字符,则这两个功能都无法在Windows上运行。

在这种情况下,可以包装现有的std::ifstream(或其他输入流)并通过ov_open_callbacks打开它。当我尝试执行此操作时,我发现the documentation略微了解所需包装函数的确切语义。

如何包装现有流以将其传递给ov_open_callbacks

最佳答案

这是一个工作示例,该示例打开一个.ogg文件并输出一些基本信息。所有包装函数(除了close,在这种情况下都不需要)都已实现,因此生成的OggVorbis_File结构是完全可搜索的。

#include <vorbis/vorbisfile.h>
#include <iostream>
#include <cassert>
#include <fstream>
#include <iomanip>
#include <vector>

size_t read(void* buffer, size_t elementSize, size_t elementCount, void* dataSource) {
    assert(elementSize == 1);

    std::ifstream& stream = *static_cast<std::ifstream*>(dataSource);
    stream.read(static_cast<char*>(buffer), elementCount);
    const std::streamsize bytesRead = stream.gcount();
    stream.clear(); // In case we read past EOF
    return static_cast<size_t>(bytesRead);
}

int seek(void* dataSource, ogg_int64_t offset, int origin) {
    static const std::vector<std::ios_base::seekdir> seekDirections{
        std::ios_base::beg, std::ios_base::cur, std::ios_base::end
    };

    std::ifstream& stream = *static_cast<std::ifstream*>(dataSource);
    stream.seekg(offset, seekDirections.at(origin));
    stream.clear(); // In case we seeked to EOF
    return 0;
}

long tell(void* dataSource) {
    std::ifstream& stream = *static_cast<std::ifstream*>(dataSource);
    const auto position = stream.tellg();
    assert(position >= 0);
    return static_cast<long>(position);
}

int main() {
    // Open file stream
    std::ifstream stream;
    stream.open("C:\\path\\to\\file.ogg", std::ios::binary);
    OggVorbis_File file;
    const ov_callbacks callbacks{read, seek, nullptr, tell};
    int result = ov_open_callbacks(&stream, &file, nullptr, 0, callbacks);
    if (result < 0) {
        std::cout << "Error opening file: " << result << std::endl;
        return 0;
    }

    // Read file info
    vorbis_info* vorbisInfo = ov_info(&file, -1);
    std::cout << "File info: " << vorbisInfo->rate << "Hz, "
        << vorbisInfo->channels << " channels" << std::endl;

    // Close file
    ov_clear(&file);
}

关于c++ - 如何使用ov_open_callbacks从流中打开Ogg Vorbis文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52121854/

10-13 07:05