我试图打开一个wav文件,读取它,将缓冲区转换为整数数组,然后将其转换回来并写入。
int main(){
ifstream file ("C:\\Documents\\ParadigmE3-shortened.wav",std::ios_base::out | std::ios_base::binary);
char * header = new char[50000044];
file.read(header, 50000044);
cout << header[0] << endl;
unsigned int * header_int = new unsigned int[50000044];
for(unsigned int i = 0; i < sizeof(header); i++){
header_int[i] = header[i];
}
char * writefile = new char[50000044];
for(unsigned int i = 0; i < sizeof(header); i++){
itoa(header_int[i], &writefile[i], 10);
}
cout << writefile[0] << endl;
ofstream newfile ("C:\\Documents\\ParadigmE3-modified.wav", std::ios_base::out | std::ios_base::binary);
newfile.write(writefile, 50000044);
}
目前,这会打印:
R
8
表示它在转换过程中更改了数据。我怎样才能让它正常工作?
经过一些建议和学习后我可以对char
变量进行计算,我重新编写了代码,现在是:
int main(){
// Create file variable with file
ifstream file ("C:\\Documents\\ParadigmE3-shortened.wav",std::ios_base::out | std::ios_base::binary);
// Read the first 15040512 bytes to char array pointer, called header
char * header = new char[15040512];
file.read(header, 15040512);
// Copy contents of header to writefile, after the 44'th byte, multiply the value by 2
char * writefile = new char[15040512];
for(int i = 0; i < sizeof(header); i++){
if(i<44) writefile[i] = header[i];
if(i>=44) writefile[i] = 2 * header[i];
}
// Copy the contents of writefile, but at the 44th byte, divide it by 2, returning it to its original value
for(int i = 0; i < sizeof(header); i++){
if(i<44) writefile[i] = writefile[i];
if(i>=44) writefile[i] = .5 * writefile[i];
}
// Create file to write to
ofstream newfile ("C:\\Documents\\ParadigmE3-modified.wav", std::ios_base::out | std::ios_base::binary);
// Write writefile to file
newfile.write(writefile, 15040512);
}
然而,在播放时(在Windows Media Player中),它不播放,所以它显然不是原始文件,正如我想要的那样。
答案 0 :(得分:0)
我明白了。我学到的一些事情是你可以对8位char
变量进行计算(最大值为255无符号),所以我不需要将它更改为int
数组,但是,我这样做是因为它给了我更多的工作空间(不用担心在255处剪切值)。
我已经包含了整个程序(带有标题包含列表),因为我也认为这是一个常见的问题,到目前为止这是我见过的最简单的方法(其他方法我不能弄清楚 - 他们做同样的事情要复杂得多。)
它读取wav文件,然后它对数据部分执行操作(从第45个字节开始),然后执行相反的操作,并写入文件,这是原始文件的副本。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <bitset>
#include <string.h>
using namespace std;
int main(){
ifstream file ("C:\\Documents\\ParadigmE3-shortened.wav",std::ios_base::out | std::ios_base::binary);
char * header = new char[15040512];
file.read(header, 15040512);
int * writefile = new int[15040512];
for(int i = 0; i < 15040512; i++){
if(i<44) writefile[i] = header[i];
if(i>=44) writefile[i] = 2 * header[i];
}
for(int i = 0; i < 15040512; i++){
if(i<44) header[i] = writefile[i];
if(i>=44) header[i] = .5 * writefile[i];
}
ofstream newfile ("C:\\Documents\\ParadigmE3-modified.wav", std::ios_base::out | std::ios_base::binary);
newfile.write(header, 15040512);
}