生成正弦波超过 1 秒时出现问题

issue when generating sine wave for more than 1 second

我几乎搜索了 SO & 几个论坛,但无法弄清楚。我没有从头开始编写代码。我得到了代码,我正在尝试根据我的要求进行修改。

所以首先归功于原始编码器。我参考这个: http://www3.nd.edu/~dthain/courses/cse20211/fall2013/wavfile/

在这里,他正在创建仅 1 秒的正弦波。但我无法超越这一点。我需要至少播放 20 秒。

这是我的代码。希望得到一些pointer/help。提前致谢。再次感谢原始编码器。

WAVFILE_SAMPLES_PER_SECOND = 44100

example.c 文件

#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 文件

#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

文件创建成功。但是我无法在任何播放器中播放它。 任何人都可以帮忙。 再次感谢

原版创建了一个1秒的wav文件。据我了解,这工作正常。以下行将 1 秒的音频写入 .wav 文件:

wavfile_write(f,waveform,length);

应该可以循环调用该线路 20 次,以获得 20 秒的音频。由于正弦波的频率为 440 Hz,因此 440 个完整的正弦波适合一秒。所以正弦在第 2 秒开始的位置与第 1 秒的位置相同。所以我觉得正弦应该是正确的。

使用原始代码,只需更改行即可获得 20 秒

const int NUM_SAMPLES = (WAVFILE_SAMPLES_PER_SECOND*2);

const int NUM_SAMPLES = (WAVFILE_SAMPLES_PER_SECOND*20);