pythonaudionoise

Generating audio noise


I would like to generate audio background noise with python and saving it in an mp3. Ideally, I can also adjust the amplitude and the frequency. Is there a package that I can use for that?

THX Lazloo


Solution

  • With scipy, you can save numpy array as a .wav file. You just need to generate a sequence of random samples from normal distribution with zero mean. truncnorm is truncated normal distribution, which makes sure the sample values are not too big or too small (+- 2^16 in case of 16 bit .wav files)

    from scipy.io import wavfile
    from scipy import stats
    import numpy as np
    
    sample_rate = 44100
    length_in_seconds = 3
    amplitude = 11
    noise = stats.truncnorm(-1, 1, scale=min(2**16, 2**amplitude)).rvs(sample_rate * length_in_seconds)
    wavfile.write('noise.wav', sample_rate, noise.astype(np.int16))