WAV File Synthesis From Scratch - C

后端 未结 1 1702
臣服心动
臣服心动 2020-12-16 03:43

Recently I saw a video lecture in my CS 101 class that inspired me to start playing with the WAV File Format in C. My project today has been creating sounds using a simple m

相关标签:
1条回答
  • 2020-12-16 04:07

    I think this is your core problem:

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

    I suspect that (time*samplerate) doesn't always increase on integer boundaries due to floating point rounding errors. Hence, some sample positions are skipped and/or overwritten due to rounding errors. That's just a guess.

    But also, as "time" increases, the multiplication of "time * frequency * 2PI" will overflow within a float. So you should normalize "time" such that it doesn't increase forever.

    In any case, I validated this modified loop works (and sounds) just fine:

    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]);
    
    }
    
    0 讨论(0)
提交回复
热议问题