커뮤니티
DSP/SPEECH
제목:    기본 연주 기본 프로그램
  847   김윤중

import numpy as np
import sounddevice as sd
import librosa

def play(sig,fs=16000) :    #play sig with sample reate fs
    sd.play(sig,fs)
    sd.wait()

def freq(o,n,kor=True) : #(4,도#,[])
    Notes_eng = {  # eng-notes and frequences on 4th octave repectively
    "C"  : 261.625000,"C#" : 277.185000,
    "D"  : 293.665000,"D#" : 311.125000,"Db" : 277.185000,
    "E"  : 329.625000,    "Eb" : 311.125000,
    "F"  : 349.230000,"F#" : 369.995000,
    "G"  : 391.995000,"G#" : 415.305000,"Gb" : 369.995000,
    "A"  : 440.000000,"A#" : 466.080000,"Ab" : 415.305000,
    "B"  : 494.000000,"Bb" : 466.080000,
    }
    Notes_kor = { # kor-notes and frequences on 4th octave repectively
    "도"  : 261.625000,"도#" : 277.185000,
    "레"  : 293.665000,"레#" : 311.125000,"레b" : 277.185000,
    "미"  : 329.625000,    "미b" : 311.125000,
    "파"  : 349.230000,"파#" : 369.995000,
    "솔"  : 391.995000,"솔#" : 415.305000,"솔b" : 369.995000,
    "라"  : 440.000000,"라#" : 466.080000,"라b" : 415.305000,
    "시"  : 494.000000,"시b" : 466.080000,
    }
    Notes = Notes_kor if kor else  Notes_eng
    f=Notes[n]*2**(o-4)    #compute frequence of o and n
    return f
def create_sig(o,n,t,A=2.0,kor=True) : # create signal 
    f=freq(o,n,kor)    #create frequence of oth oactave and note n
    s=A*np.sin(2*np.pi*f*t)    #create sig of freq f
    return s

if __name__== "__main__" :
    fs=16000            #fmax=8KHz
    duration=1            #sec
    t=np.linspace(0,duration,duration*fs) #

    notes=[create_sig(4,'도',t)]            # sig of 도 of 4th octave for 1 sec
    notes.append(create_sig(4,'레',t))    # sig of 레 of 4th octave for 1 sec
    notes.append(create_sig(4,'미',t))
    notes.append(create_sig(4,'파',t))
    notes.append(create_sig(4,'솔',t))
    notes.append(create_sig(4,'라',t))
    notes.append(create_sig(4,'시',t))
    notes.append(create_sig(5,'도',t))

    notes.append(create_sig(4,'솔',t))
    notes.append(create_sig(4,'솔',t))
    notes.append(create_sig(4,'미',t[:len(t)//2]))  # for 0.5sec
    notes.append(create_sig(4,'파',t[:len(t)//2]))    # for 0.5sec
    notes.append(create_sig(4,'솔',t))

    x=np.array([])
    for sig in notes :        #merge all sigs to one siganl on x
        x=np.append(x,sig)
    play(x,fs)                #play sig x
    librosa.output.write_wav('piano.wav',x,fs)    #save wave sig

    y,sr=librosa.load('piano.wav',fs)    #load wave sig y
    play(y,fs)                #play sig y
    librosa.output.write_wav('piano.wav',y,fs)    #save wave sig

생성된 signal piano.wav