首页 > 解决方案 > 如何在 C++ 中的数组中加载 Wav 文件?

问题描述

嘿,我有一个动态数组,我想将我的 Wav 文件的数据加载到这个数组中,我已经写了开头但我不知道如何将文件加载到我的动态数组中,有人可以进一步帮助我用这个代码?

#include <iostream> 
using namespace std;

template <typename T> 
class Array{
public:
    int size;
    T *arr;

    Array(int s){
    size = s;
    arr = new T[size];
    }

    T& operator[](int index)
    {
        if (index > size)
            resize(index);
        return arr[index];
    }

 void resize(int newSize) { 
        T* newArray = new T[newSize];
        for (int i = 0; i <size; i++)
        {
            newArrayi] = arr[i];
        }
        delete[] arr;
        arr = newArray;
        size = newSize;
    }
};
int main(){

    Array<char> wavArray(10);
    FILE  *inputFile;
    inputFile =fopen("song.wav", "rb");

        return 0;
}

标签: c++arraystemplateswav

解决方案


如果您只想将完整的文件加载到内存中,这可能会派上用场:

#include <iterator>

// a function to load everything from an istream into a std::vector<char>
std::vector<char> load_from_stream(std::istream& is) {
    return {std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>()};
}

...并使用 C++ 文件流类打开和自动关闭文件。

{
    // open the file
    std::ifstream is(file, std::ios::binary);

    // check if it's opened
    if(is) {
        // call the function to load all from the stream
        auto content = load_from_stream(is);

        // print what we got (works on textfiles)
        std::copy(content.begin(), content.end(),
                  std::ostream_iterator<char>(std::cout));
    } else {
        std::cerr << "failed opening " << file << "\n";
    }
}

...但是 WAV 文件包含许多描述文件内容的不同块,因此您可能希望创建单独的类以将这些块流式传输到文件和从文件流式传输。


推荐阅读