c - 从头开始合成 WAV 文件 - C

标签 c math audio signal-processing pitch

最近,我在 CS 101 类(class)中看到了一个视频讲座,它启发了我开始使用 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;

}

最佳答案

我认为这是你的核心问题:

*(sound + (int)(time * samplerate)) = total;

我怀疑由于浮点舍入误差,(time*samplerate) 并不总是在整数边界上增加。因此,一些样本位置由于舍入误差而被跳过和/或覆盖。这只是一个猜测。

而且,随着“时间”的增加,“时间 * 频率 * 2PI”的乘积将在 float 内溢出。因此,您应该规范化“时间”,使其不会永远增加。

无论如何,我验证了这个修改后的循环工作(和声音)都很好:

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]);

}

关于c - 从头开始合成 WAV 文件 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10844122/

相关文章:

c - 将 Tag 添加到类型声明

C 编程 : Saving value in for loop and finding minimum

java - vector 数学中的大 float

java - 添加两个多头会带来较低的结果

c# - 如何渲染音频波形?

c++ - 一个union需要多少内存

c - 循环的时间复杂度

math - 将任意长度转换为 -1.0 到 1.0 之间的值?

ios - 如何在 iOS 上使用 Xamarin 播放音调

android - 某些 QSoundEffects 无法在 Android 上播放(永远)