c++ - 如何在 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;
}
解决方案
如果您只想将完整的文件加载到内存中,这可能会派上用场:
#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 文件包含许多描述文件内容的不同块,因此您可能希望创建单独的类以将这些块流式传输到文件和从文件流式传输。
推荐阅读
- python - 如果第一个场景在 Python Behave 中失败,则跳过第二个场景
- python - 遍历数组以找到最高配对
- javascript - 如何保存我的数据表数据 ASP.NET MVC 5
- html - 如何在保持纵横比的同时将画布的最大宽度设置为屏幕大小?
- django - 将 LoginView 重定向到用户特定的帐户/个人资料 URL
- java - 我们可以使用bindy在多个级别解析带有分隔符的记录吗
- python - 将 Eigen 库与 cppyy 一起使用
- ios - 在 iOS 框架中嵌入 .dylib
- python - 大熊猫,lambda内的比较
- javascript - 如何在字符串中找到时间戳,然后转换为小时/分钟数?