User Tools

Site Tools


pcmsoundgen
sinsound.py
#/usr/bin/env python3
 
from math import *
import sys, array
 
def SoundSin(freq=1000, vol=0.5, func=sin, sample_rate=44100):
    """Returns a sound function. I.e. function which returns value in
    range -1 to 1 representing PCM sample
 
    Keyword arguments:
    freq -- tone frequency in Hz (default 1000)
    vol -- volume from 0 to 1 (default 0.5)
    func -- function to generate tone (default sin)
    sample_rate -- sample rate of tone (default 44100)
 
    """
    return lambda t: vol * func(2 * pi * freq * t / sample_rate)
 
def SoundSquare(**kwargs):
    kwargs['func'] = lambda t: float(sin(t) > 0) * 2 - 1
    return SoundSin(**kwargs)
 
t = 0
buf = []
# here add tones
sounds = [SoundSin(freq=300), SoundSin(freq=600, func=cos, vol=0.3)]
while True:
    t += 1
    if t >= 44100:
        array.array('f', buf).tofile(sys.stdout.buffer)
        t = 0
        buf = []
 
    buf.append(sum(s(t) for s in sounds))

Usage (linux and pulseaudio):

# CTRL-C to stop
python3 sinsound.py | pacat  --channels=1 --format=float32ne
pcmsoundgen.txt · Last modified: 2015/12/16 23:16 by dominik