I have searched almost SO & few forums, but unable to figure out. I have not coded this from scratch. I got the code and I am trying to modify as per my requirement.
So firstly credits to original coder. I am ref this : http://www3.nd.edu/~dthain/courses/cse20211/fall2013/wavfile/
Here he is creating the sine wave for just 1 second. But I am unable to surpass this point. I need to play it for atleast 20seconds.
Here is my code. Hope to get some pointer/help. Thanks in advance. Again thanks to original coder.
WAVFILE_SAMPLES_PER_SECOND = 44100
example.c file
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include "wavfile.h"
const int NUM_SAMPLES = (WAVFILE_SAMPLES_PER_SECOND*2);
int main()
{
unsigned long waveform[NUM_SAMPLES*4]; // here I am changing it to 4
double frequency = 440;
int volume = 255;
unsigned long int length = NUM_SAMPLES*4; // here I am changing it to 4
// For one second the length = 88200
unsigned long int i;
for(i=0;i<length;i++) {
long double t = (long double) i / WAVFILE_SAMPLES_PER_SECOND;
waveform[i] = volume*sin(frequency*t*2*M_PI);
}
printf("length=%d\n",length);
FILE * f = wavfile_open("sound.wav");
if(!f) {
printf("couldn't open sound.wav for writing: %s",strerror(errno));
return 1;
}
wavfile_write(f,waveform,length);
wavfile_close(f);
return 0;
}
wave.h file
#ifndef WAVFILE_H
#define WAVFILE_H
#include <stdio.h>
#include <inttypes.h>
FILE * wavfile_open( const char *filename );
void wavfile_write( FILE *file, short data[], int length );
void wavfile_close( FILE * file );
#define WAVFILE_SAMPLES_PER_SECOND 44100
#endif
The file is created successfully. But I am unable to play it in any player. Can any one help. Thanks again
答案 0 :(得分:2)
With the original code, to get 20 seconds you just need to change the line
const int NUM_SAMPLES = (WAVFILE_SAMPLES_PER_SECOND*2);
to
const int NUM_SAMPLES = (WAVFILE_SAMPLES_PER_SECOND*20);
答案 1 :(得分:1)
In the original version a wav file of 1 second was created. As I understand that was working fine. The following line writes 1 second of audio tho the .wav file:
wavfile_write(f,waveform,length);
It should be possible to call that line 20 times in a loop, to get 20 seconds of audio. As the frequency of the sine is 440 Hz, 440 full sines fit into a second. So the sine is at the same position at the start of the 2nd second as it was at the 1st. So I think the sine should be correct.