Deep
Deep

Reputation: 2512

Why corrupt sound?

For this code:

while (1) {
    generate_noise(frames, period_size);
    snd_pcm_writei(dev, frames, period_size);
}

it works fine..

But for this:

generate_noise(frames, period_size);
while (1) {
    snd_pcm_writei(dev, frames, period_size);
}

Sound is broken. Each iteration has an audible crack! This causes always update buffer. Why?

UPD:

typedef struct {
    int16_t left;
    int16_t right;
} pcm_frame;

...

void
generate_noise(pcm_frame *frames, const size_t size)
{
    size_t pos = 0;

    while (pos < size) {
        frames[pos].left  = rand() % 200;
        frames[pos].right = rand() % 200;
        pos += 1;
    }
}

Upvotes: 0

Views: 103

Answers (1)

Dietrich Epp
Dietrich Epp

Reputation: 213578

This generates aperiodic white noise.

while (1) {
    generate_noise(frames, period_size);
    snd_pcm_writei(dev, frames, period_size);
}

This generates a periodic waveform... NOT noise! The human ear is an amazing machine and it can actually tell that you are reusing the same noise over and over again.

generate_noise(frames, period_size);
while (1) {
    snd_pcm_writei(dev, frames, period_size);
}

At 48 kHz, with a period of 1024 samples, it will generate a note at 46.9 Hz, which is close to the third G below middle C. The note will have lots of recognizeable overtones, and it will NOT sound like white noise.

If you want white noise, you can't have it loop so quickly... because making it loop makes it periodic, which means it's a recognizable note. If you want it to loop, you'll have to make the loop longer.

Upvotes: 2

Related Questions