Skip to content

Instantly share code, notes, and snippets.

@endolith
Last active June 10, 2016 03:17
Show Gist options
  • Select an option

  • Save endolith/1072063 to your computer and use it in GitHub Desktop.

Select an option

Save endolith/1072063 to your computer and use it in GitHub Desktop.
Mono and stereo sine .wav generation with PySoundFile
"""
Testing with subtype='PCM_24' confirms that quantization distortion is from
encoding.
Waves are scaled -1 dB to prevent clipping.
"""
from __future__ import division
from soundfile import write
from numpy import transpose, pi, linspace, sin
from numpy.random import uniform
fs = 44100 # samples per second
length = 3 # seconds
f_L = 500 # Hz
f_R = 200 # Hz
t = linspace(0, length, num=fs * length, endpoint=False)
x_L = 0.891 * sin(2 * pi * f_L * t)
x_R = 0.891 * sin(2 * pi * f_R * t)
write('mono.wav', x_L, fs, subtype='PCM_16')
write('stereo.wav', transpose([x_L, x_R]), fs, subtype='PCM_16')
"""
Dither attempt:
I don't know if noise is scaled optimally, but it seems right.
"""
x = 0.891 * sin(2 * pi * f_L * t)
dither = uniform(low=-1/2**16, high=1/2**16, size=len(t))
write('dithered.wav', x + dither, fs, subtype='PCM_16')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment