Search code examples
pythonnumpyalsa

How to synthesize sounds?


I'd like to produce sounds that would resemble audio from real instruments. The problem is that I have very little clue how to get that.

What I know this far from real instruments is that sounds they output are rarely clean. But how to produce such unclean sounds?

This far I've gotten to do this, it produces quite plain sound from which I'm not sure it's even using the alsa correctly.

import numpy
from numpy.fft import fft, ifft
from numpy.random import random_sample
from alsaaudio import PCM, PCM_NONBLOCK, PCM_FORMAT_FLOAT_LE

pcm = PCM()#mode=PCM_NONBLOCK)
pcm.setrate(44100)
pcm.setformat(PCM_FORMAT_FLOAT_LE)
pcm.setchannels(1)
pcm.setperiodsize(4096)

def sine_wave(x, freq=100):
    sample = numpy.arange(x*4096, (x+1)*4096, dtype=numpy.float32)
    sample *= numpy.pi * 2 / 44100
    sample *= freq
    return numpy.sin(sample)

for x in xrange(1000):
    sample = sine_wave(x, 100)
    pcm.write(sample.tostring())

Solution

  • Cheery, if you want to generate (from scratch) something that really sounds "organic", i.e. like a physical object, you're probably best off to learn a bit about how these sounds are generated. For a solid introduction, you could have a look at a book such as Fletcher and Rossings The Physics of Musical Instruments. There's lots of stuff on the web too, you might want to have a look at a the primer James Clark has here

    Having at least a skim over this sort of stuff will give you an idea of what you are up against. Modeling physical instruments accurately is very difficult!

    If what you want to do is have something that sounds physical, rather something that sounds like instrument X, your job is a bit easier. You can build up frequencies quite easily and stack them together, add a little noise, and you'll get something that at least doesn't sound anything like a pure tone.

    Reading a bit about Fourier analysis in general will help, as will Frequency Modulation (FM) techniques.

    Have fun!