Created
October 12, 2012 10:54
-
-
Save mckelvin/3878675 to your computer and use it in GitHub Desktop.
音符模拟发生
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# coding: UTF-8 | |
import time | |
import numpy as np | |
from numpy.fft import fft, ifft | |
from numpy.random import random_sample | |
from alsaaudio import PCM, PCM_NONBLOCK, PCM_FORMAT_FLOAT_LE | |
C_freq = np.float128(440) | |
magic = 2 ** (1/12.) | |
init_freq = C_freq * (magic ** -(4 * 12 + 9)) #C0 | |
note = ['C', 'C♯/D♭', 'D', 'D♯/E♭', 'E', 'F', 'F♯/G♭', 'G', 'G♯/A♭', 'A', 'A♯/B♭', 'B'] | |
octave = range(11) | |
srate = 44100 | |
dur = 44100 | |
pcm = PCM()#mode=PCM_NONBLOCK) | |
pcm.setrate(srate) | |
pcm.setformat(PCM_FORMAT_FLOAT_LE) | |
pcm.setchannels(1) | |
pcm.setperiodsize(dur) | |
def sine_wave(x, freq=100): | |
sample = np.arange(x*dur, (x+1)*dur, dtype=np.float32) | |
sample *= np.pi * 2 / srate | |
sample *= freq | |
return np.sin(sample) | |
for i in xrange(len(octave)): | |
for j in xrange(len(note)): | |
x = i * len(octave) + j | |
sample = sine_wave(x, init_freq) | |
pcm.write(sample.tostring()) | |
print '%s\'th beep with octave:%s, note:%s, freq:%s' % \ | |
(x + 1,octave[i],note[j],init_freq) | |
time.sleep( float(srate/dur) ) | |
init_freq *= magic | |
pcm.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment