Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate a note or chord in python?

Tags:

python

audio

Can anybody point me to a good library for generating notes and chords in python 2.7? I have looked at the PythonInfoWiki without a lot of luck, PyAudio just crashes and nothing else seems to generate tones.

like image 317
philosodad Avatar asked Feb 24 '23 22:02

philosodad


1 Answers

I don't know if it will help, but here's some code that synthetizes a complex sound based on gives frequencies and amplitudes:

import math
import wave
import struct

def synthComplex(freq=[440],coef=[1], datasize=10000, fname="test.wav"):
    frate = 44100.00  
    amp=8000.0 
    sine_list=[]
    for x in range(datasize):
        samp = 0
        for k in range(len(freq)):
            samp = samp + coef[k] * math.sin(2*math.pi*freq[k]*(x/frate))
        sine_list.append(samp)
    wav_file=wave.open(fname,"w")
    nchannels = 1
    sampwidth = 2
    framerate = int(frate)
    nframes=datasize
    comptype= "NONE"
    compname= "not compressed"
    wav_file.setparams((nchannels, sampwidth, framerate, nframes, comptype, compname))
    for s in sine_list:
        wav_file.writeframes(struct.pack('h', int(s*amp/2)))
    wav_file.close()

synthComplex([440,880,1200], [0.4,0.3,0.1], 30000, "tone.wav")

That's the code i'm using to generate notes and chords in python. You shold have a frequencies list for the first parameter, an amplitude list (same size as the first) , a number of samples and the name of the file. It will generate a wav file with the given combination.

like image 170
Nemeth Avatar answered Feb 27 '23 12:02

Nemeth