How to load a Wav file in an Array in C++?

China☆狼群 提交于 2019-12-13 03:58:20

问题


Hey I've a dynamic array and I want to load to this array the data of my Wav file, I already wrote the beginning but I can't figure it out how to load the file in my dynamic array, can somebody help me further with this code?

#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;
}

回答1:


if you just want to load the complete file into memory, this may come in handy:

#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>()};
}

... and use the C++ file streaming classes to open and automatically close files.

{
    // 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";
    }
}

... but a WAV file contains a lot of different chunks describing the contents of the file so you may want to create individual classes for streaming these chunks to and from files.




回答2:


char* readFileBytes(const char *name)  
{  
    FILE *fl = fopen(name, "r");  
    fseek(fl, 0, SEEK_END);  
    long len = ftell(fl);  
    char *ret = malloc(len);  
    fseek(fl, 0, SEEK_SET);  
    fread(ret, 1, len, fl);  
    fclose(fl);  
    return ret;  
}  


来源:https://stackoverflow.com/questions/56135248/how-to-load-a-wav-file-in-an-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!