我试图创建一个产生10秒C音符的C代码。但是输出的.wav文件似乎没有发出声音。
我还是C编程的新手,如果您能指出我的错误,对您会有所帮助。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
//music note
#define C 261.6256
#define TIME 10
#define POINT 20
#define AMP 10000
#define c 5
//wav file header
typedef struct
{
char ChuckID[4];
unsigned long ChuckSize;
char format[4];
char subChunk1ID[4];
unsigned long SubChunk1Size;
unsigned short AudioFormat;
unsigned short NumChannels;
unsigned long SampleRate;
unsigned long ByteRate;
unsigned short block_allign;
unsigned short bits_per_sample;
char data[4];
unsigned long data_size;
/*char riff_tag[4];
int riff_length;
char wave_tag[4];
char fmt_tag[4];
int fmt_length;
short audio_format;
short num_channels;
int sample_rate;
int byte_rate;
short block_align;
short bits_per_sample;
char data_tag[4];
int data_length;*/
} wavheader;
int main(int argc, char **argv)
{
wavheader wave = {"RIFF",1764036,"WAVE","fmt",16,1,1,44100,176400,4,32,"data",1764000};
float data;
float f = C;
int fs = 44100;
int k;
float *buff;
FILE *out_file = fopen("ongaku.wav","w");
buff = (float*)malloc(sizeof(float)*fs*TIME);
for (k = 0; k<(int)(TIME*fs); k++)
{
data=AMP*sin(2*M_PI*f*k/fs);
//printf("%f\n",data);
}
fwrite(buff,sizeof(float),fs*TIME,out_file);
return 0;
}
最佳答案
我可以使用8位数据,但是不能使用12/16位,更不用说float
数据了。重要的一件事是不要在 header 中硬编码缓冲区大小。需要注意的其他方面是字节序(我碰巧不需要调整)和结构打包(同上)。当使用12位数据时,我对BPS/8
的使用也不会卡住。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define FREQ 261.6256 // C
//#define FREQ 440.0 // A
#define M_PI 3.14159265358979323846
#define TIME 10
#define AMP 64.0 // don't use max volume
#define MID 128.0 // 8-bit is range 0..255
//#define MID 0.0 // 16-bit is range -32767.. 32767
#define BPS 8
#define CHANNS 1
#define RATE 44100
//wav file header
typedef struct {
char ChuckID[4];
unsigned long ChuckSize;
char format[4];
char subChunk1ID[4];
unsigned long SubChunk1Size;
unsigned short AudioFormat;
unsigned short NumChannels;
unsigned long SampleRate;
unsigned long ByteRate;
unsigned short block_allign;
unsigned short bits_per_sample;
char data[4];
unsigned long data_size;
} wavheader;
int main(int argc, char **argv)
{
int k, samples = RATE * TIME;
double data;
FILE *out_file;
unsigned char *buff;
wavheader wave = {
"RIFF",
36 + samples * CHANNS * BPS/8,
"WAVE",
"fmt ", // "fmt" was error in OP
16,
1,
CHANNS,
RATE,
RATE * CHANNS * BPS/8,
CHANNS * BPS/8,
BPS,
"data",
samples * CHANNS * BPS/8
};
buff = malloc(BPS/8 * samples);
out_file = fopen("ongaku.wav","w");
fwrite(&wave, sizeof(wave), 1, out_file);
for (k=0; k<samples; k++) {
data = MID + AMP * sin(2 * M_PI * FREQ * TIME * k / (double)samples);
buff[k] = (unsigned char)floor(data+0.5);
}
fwrite(buff, BPS/8, samples, out_file);
fclose (out_file);
free (buff);
return 0;
}
关于c - C输出Wav文件未产生任何声音,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27657155/