从头开始合成WAV文件 - C

8
最近在我的CS 101课程中,我看到一个视频讲座,激发了我开始用C语言玩WAV文件格式。 我今天的项目是使用简单的正弦函数创建声音。尽管遇到了一些障碍,但我的程序现在可以接受多个输入(波形频率,波形振幅,采样率等),并生成包含指定音高的wav文件。
然而,在我的计算机扬声器上播放这些音调时,会听到奇怪的、有节奏的爆裂声,其频率随着采样率的提高而增加,并变成令人讨厌的嗡嗡声。
奇怪的是,爆裂声在不同的计算机上使用相同的文件也是一致的。
下面我将发布用于生成WAV文件的代码。任何关于可能导致这种现象的见解都将不胜感激。这可能只是因为我犯了一个愚蠢的错误。 :)
#include <stdio.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <string.h>
#include <math.h>

struct WAVHeader {
    char ChunkID[4];
    uint32_t ChunkSize;
    char RIFFType[4];
};

struct FormatHeader {
    char ChunkID[4];
    uint32_t ChunkSize;
    uint16_t CompressionCode;
    uint16_t Channels;
    uint32_t SampleRate;
    uint32_t AvgBytesPerSec;
    uint16_t BlockAlign;
    uint16_t SigBitsPerSamp;
};

struct DataHeader {
    char ChunkID[4];
    uint32_t ChunkSize;

};


void main(int argc, char * argv[]) {

//Check for valid number of arguments or display help
if(argc < 8) {
    printf("Usage:\n./Tone -l [length] -s [frequency] [amplitude] -o [output-file] -r [sample-rate]\n");
    printf("-l length of tone to produce in seconds\n");    
    printf("-s Creates sine wave. Can be used multiple times. Frequency (Hz) and amplitude (0 - 32767) of each tone. \n");  
    printf("-o File to write to\n");
    printf("-r samples per second (kHz). Note: Must be double highest frequency in tone.\n");   
    return;
}

//Organize arguments
int length, sinf[10], sina[10], samplerate;
memset(sinf, 0, sizeof(int) * 10);
memset(sina, 0, sizeof(int) * 10);
char * output = NULL;
int i = 0;
int count;
for(count = 1; count < argc; count++){
    char first = *argv[count];
    int second = *(argv[count] + 1);    
    if (first == '-') {
        switch (second) {
            case 's':
                sinf[i] = atoi(argv[count+1]);
                sina[i] = atoi(argv[count+2]);
                i++;
                break;
            case 'l':
                length = atoi(argv[count+1]);
                break;
            case 'o':
                output = argv[count+1];
                break;
            case 'r':
                samplerate = atoi(argv[count+1]) * 1000;
                break;
        }
    }
}

//Allocate memory for wav file
size_t size = sizeof(struct WAVHeader) + sizeof(struct FormatHeader) + sizeof(struct DataHeader) + (length * samplerate * 2);
void * buffer = malloc(size);

//Fill buffer with headers
struct WAVHeader * WAV = (struct WAVHeader *)buffer;
struct FormatHeader * Format = (struct FormatHeader *)(WAV + 1);
struct DataHeader * Data = (struct DataHeader *)(Format + 1);

strcpy(WAV->ChunkID, "RIFF");
WAV->ChunkSize = (uint32_t)size - 8;
strcpy(WAV->RIFFType, "WAVE");

strcpy(Format->ChunkID, "fmt ");
Format->ChunkSize = 16;
Format->CompressionCode = 1;
Format->Channels = 1;
Format->SampleRate = (uint32_t)samplerate;
Format->SigBitsPerSamp = 16;
Format->BlockAlign = 2;
Format->AvgBytesPerSec = Format->BlockAlign * samplerate;

strcpy(Data->ChunkID, "data");
Data->ChunkSize = length * samplerate * 2;

//Generate Sound
printf("Generating sound...\n");
short * sound = (short *)(Data + 1);
short total;
float time;
float increment = 1.0/(float)samplerate;
for (time = 0; time < length; time += increment){
    total = 0;
    for (i = 0; i < 10; i++) {
        total += sina[i] * sin((float)sinf[i] * time * (2 * 3.1415926));
    }
    *(sound + (int)(time * samplerate)) = total;
    //printf("Time: %f Value: %hd\n", time, total);
}

//Write buffer to file
FILE * out = fopen(output, "w");
fwrite(buffer, size, 1, out);
printf("Wrote to %s\n", output);

return;

}

如果没有使用“-r”选项,那么samplerate会发生什么? - thb
这不是你的问题,但你应该使用memcpy而不是strcpy,因为它会复制尾随的'\0'。 - Michael Anderson
很好的发现,@Michael。我很惊讶它还没有把整个东西搞砸。 :) - Kokopelli
哦。它没有搞砸的原因是我在犯错后立即覆盖它。好吧。如果我不能做得好,那我还不如幸运一些。:D - Kokopelli
顺便提一下,我还需要包含 stdint.h 和 stdlib.h 才能编译(并且需要使用 gcc -lm 进行链接)。 - Jeremy Leipzig
1个回答

7
我认为这是你的核心问题:
*(sound + (int)(time * samplerate)) = total;

我怀疑由于浮点数舍入误差,(时间*采样率)不总是在整数边界上增加。因此,由于舍入误差,一些样本位置被跳过和/或覆盖。这只是一个猜测。
此外,随着“时间”的增加,“时间*频率*2PI”的乘积将在浮点数内溢出。因此,您应该规范化“时间”,使其不会永远增加。
无论如何,我已验证这个修改后的循环可以正常工作(并且声音也很好听):
float TWOPI = 6.28318531f;
unsigned int sample_count = length * samplerate;

for (unsigned int i = 0; i < sample_count; i++)
{
    unsigned int j = i % samplerate; // normalize the sample position so that we don't blow up in the subsequent multiplication
    float f = 0.0f;
    int result;

    for (int x = 0; x < 10; x++)
    {
        f += sina[x] * sin((sinf[x] * j * TWOPI) / samplerate);
    }

    result = (long)f;

    //clamp to 16-bit
    if (result > 32767)
    {
        result = 32767;
    }
    else if (result < -32768)
    {
        result = -32768;
    }

    sound[i] = (short)result;

    //printf("%d\n", sound[i]);

}

循环到10是为了支持最多10个正弦波的累加。 - Michael Anderson
哦,我明白了。我更新了我的答案,包括他的数组循环。并且在将浮点数转换回短整型之前正确地夹紧了他的结果。 - selbie
谢谢@selbie的建议。我会尝试一下,看看它是否能治好我的问题。 - Kokopelli
非常感谢你,Selbie。一切听起来都很棒。现在我要去做音乐了。 - Kokopelli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接