2013년 3월 18일 월요일

[python sound] chirp, sweep wave 만들기

chirp, sweep하는 정형파 만들기

Sine wave의 주파수가 일정하게 변하면서 모든 주파수를 들을 수 있다.
개인적으로 고주파를 들을 때 귀가 아픈게 짜증나지만 -.-

아래 예제는
10Hz~20kHz 주파수를 일정한 크기로 만들었지만,
사람의 청각 특성 때문에 귀로 들을 때는 일정한 크기로 들리지 않는다.

여기서 만든 wav 파일로 앞으로 만들 필터를 검증하는데 이용하려고 한다.

import math
import wave
import struct
import scipy
import numpy as np
import matplotlib.pyplot as plt

freq = 1000.0
data_size = 20*44100
fname = "ChirpWave.wav"
frate = 44100.0
amp = 64000.0     # multiplier for amplitude

t = np.arange(0, data_size/frate, 1/frate)
y= scipy.signal.chirp(t, f0=10, f1=20000, t1=5, method='linear')

wav_file = wave.open(fname, "w")

nchannels = 1
sampwidth = 2
framerate = int(frate)
nframes = data_size
comptype = "NONE"
compname = "not compressed"

wav_file.setparams((nchannels, sampwidth, framerate, nframes,
    comptype, compname))

for s in y:
    # write the audio frames to file
    wav_file.writeframes(struct.pack('h', int(s*amp/2)))

wav_file.close()



참고 :
위키백과 : http://en.wikipedia.org/wiki/Chirp

http://www.scipy.org/Cookbook/FrequencySweptDemo
http://docs.scipy.org/doc/scipy/scipy-ref.pdf

2013년 3월 15일 금요일

[python sound] 간단한 FIR 필터 만들기

간단한 FIR 필터 만들기

간단한 FIR 필터를 만듦. 예제로 moving average 필터를 사용함.
예전 예제에서 만든 wav file(".\WaveTest.wav")을 이용함

 import wave
import struct

import numpy as np
import matplotlib.pyplot as plt

N = 20 #FIR filter length

fname = ".\WaveTest.wav"
wav_file = wave.open(fname, "r")

framerate = float(wav_file.getframerate())
nframes = wav_file.getnframes()

time = np.arange(0, nframes/framerate, 1/framerate)
x = []
for i in range(nframes):
    waveData = wav_file.readframes(1)
    x.append(struct.unpack("
wav_file.close()

b = [1.0/N]*N #FIR filter coefficient, moving averaging filter

#Filtering mechanism
#y[n] = b[0]*x[n] + b[1]*x[n-1] + b[2]*x[n-2] + ... + b[n-1]*x[1] + b[n]*x[0]

'''
y = [0.0]*nframes
for index in range(nframes):
    for k in range(N):
        if index-k >= 0:
            y[index] = y[index] + b[k]*x[index-k]
'''
y = np.convolve(b, x, "full")
            
plt.plot(time, x, time, y)
plt.xlabel("times[s]")
plt.ylabel("data")
plt.xlim(0, 0.005)
plt.show()


필터링 된 이미지


참고 :
위키백과 : http://en.wikipedia.org/wiki/Finite_impulse_response
scipy가 지원하는 fir filter : http://mpastell.com/2010/01/18/fir-with-scipy/

2013년 3월 14일 목요일

[python sound] wav 파일 만들기

임의적으로 sine 파형을 만들어 wave 파일로 저장하는 python code

1kHz sine wav 파일 만들기

import math
import wave
import struct

freq = 1000.0
data_size = 40000*4
fname = "WaveTest.wav"
frate = 44100.0
amp = 64000.0     # multiplier for amplitude

sine_list_x = []
for x in range(data_size):
    sine_list_x.append(math.sin(2*math.pi*freq*(x/frate)))

wav_file = wave.open(fname, "w")

nchannels = 1
sampwidth = 2
framerate = int(frate)
nframes = data_size
comptype = "NONE"
compname = "not compressed"

wav_file.setparams((nchannels, sampwidth, framerate, nframes,
    comptype, compname))

for s in sine_list_x:
    # write the audio frames to file
    wav_file.writeframes(struct.pack('h', int(s*amp/2)))

wav_file.close()
import os
os.startfile(fname)



참조 : http://stackoverflow.com/questions/3637350/how-to-write-stereo-wav-files-in-python

Reading
위 코드에서 저장한 wav file을 읽어 그래프로 보는 python code 임.

import wave
import struct

import numpy as np
import matplotlib.pyplot as plt

fname = ".\WaveTest.wav"
wav_file = wave.open(fname, "r")

framerate = float(wav_file.getframerate())
nframes = wav_file.getnframes()

time = np.arange(0, nframes/framerate, 1/framerate)
data = []
for i in range(0,nframes):
    waveData = wav_file.readframes(1)
    data.append(struct.unpack("

wav_file.close()

plt.plot(time, data)
plt.xlabel("times[s]")
plt.ylabel("data")
plt.xlim(0, 0.01)
plt.show()


참조1 : http://stackoverflow.com/questions/2060628/how-to-read-wav-file-in-python
참조2 : http://matplotlib.org/faq/usage_faq.html
down : matplotlib, numpy

이상!!

2013년 2월 25일 월요일

[그리니워즈] 영어mp3 찾기


"http://www.gstatic.com/dictionary/static/sounds/de/0/"+eng+".mp3"

2012년 12월 27일 목요일

[생각]돈에 대한 고찰


돈은 무엇이든 할 수 있는가.
가끔 돈에 대한 갈망이 큰 굶주린자는 화낸 듯 묻는다.
"돈으로 못하는게 뭔데?"

난 되묻는다. "도대체 돈으로 할 수 있는게 뭐야?"
내가 정말로 원하는 것은 돈으로 할 수 없다.
이 세상을 떠나버린 사랑하는 사람을 되돌릴 수 없고
내 생을 영원히 지켜주지도 못한다.
빛의 속도를 마음대로 조절하지 못하고
시간 여행을 보내주지 못한다.
신을 내 눈앞에 대려다주지도 못하고
사후세계를 보여주지도 않는다.

돈은 양식을 주고 입을 것, 잘 곳을 제공한다.
더불어 뭔가를 할 때 좀 더 편리하고 정확하게 해주고
풍족하고 사치스러운 생활을 영위하게 해준다.
돈은 어떤 목적을 위한 도구에 불과하다.

돈이 중요한 것은 있을 때가 아니다.
돈이 없으면 생존의 위협받는 것이 중요한 것이다.
돈이 없으면 먹을 것도 입을 것도 잘 곳도 없다.
이것은 자본주의의 병폐 중 하나이지만
자본주의를 이끄는 원동력이기도 하다.

많은 직장인들이 밥먹으러 갈때
웃으갯소리로 돈버는 것을 "먹으려 하는짓"이라고 한다.
많은 부모들이 아이들을 키우는 걱정에
한숨과 눈물을 삼키고 일하러 나간다.

일명 기업에서 사용자라 일컷는 이들이
노동자들을 일을 시키는 원동력은
돈이 없으면 생존이 어렵다는 것이다.
재벌들은 노동자를 생존을 담보로
일을 시키고 돈을 벌어오게 한다.

자본주의를 뛰어넘어 복지국가로 갈 수 있을까.
복지는 생존의 문제를 해결해 준다.
그렇다면 돈을 벌 이유가 없어진다.
사치를 위해 돈을 벌 사람이 얼마나 있겠는가.
공산주의가 일하는 사람이 없어 망해버리는 것처럼
복지국가도 마찬가지가 될 것이다.

하지만.
누구도 아무것도 하지 않고 살지는 않는다.
TV나 PC도 사치적이라는 것을 인지하라.
노는 것 또한 돈이 드는 것이다.
결국 어떠한 일을 하게될것이다.

가장 이상적인 직장은
급여가 높은 곳이 아니라 꿈이 있는 곳이다.
꿈을 이루는 것, 쉽게말해 하고 싶은 일을 하는 것
그 전에 꿈을 갖게하는 교육

물론 단순 노동을 해야하는 직업도 많지만
그러한 일에는 높은 급여와 사치로 보상해주어야할 것이다.
더이상 높으신 양반 놈들을 위해
노예처럼 일해야는 세상은 없어지길 바라며...

2012년 1월 7일 토요일

자동급지 스캐너는 그냥 단면되는 거로 사야됨..

아놔... 괜히 양면 급지용으로 비싸게 샀는데 못쓴다...
HP 꺼로 샀는데 굉장히 느린데다가,
양면의 경우엔, 규격화된 A4가 아니면 스캔이 느려지게 되서 이상하게 된다.
회사에 신도리코 스캐너가 들어와서
빠른 속도로 양면스캔이 된다고 좋아했는데...
가로로 스캔하면 한쪽 면이 짤리고..
세로로 스캔하자니 계속 종이가 걸린다... 어쩌라고.. ㅡ,.ㅡ;;
결국 단면 스캔으로 다했다....
jpg로 스캔해서... 이름 수정해서 pdf 만드는 프로그램 만들어야 겠다...
젠장...
걍 단면 스캐너로 살껄....

2010년 2월 7일 일요일

토마토 보카칩 단어 모음

day10
reasonably delegate atmosphere nearby former appliance occupation administration federal eliminate complement tow undergo workplace regardless aisle transit commission hesitate packet transaction payroll strict ingredient familiar influence estate adequate implement accomplish portion blueprint

day11
refuse memorandum outline duplicate insulation assign critical expire oversee conclusion respect admission satisfactory paycheck suburban tariff personality domestic suspend coverage interfere keynote qualification substantial prospective content proof commitment extensive pollution commute merge

day12
suitable exceed crew dedicated stack otherwise courier expedite steering experiment booklet comprehensive polish grocery retain assure status utility publicity draft paperwork complete occur auditorium relevant protective transmission equip portable vacancy emphasize prohibit

day13
correspondence absolute streamline lack itinerary compose confidence affair raw thorough superior assume routine clarify appraisal restructuring complimentary compile inflation urgent designate surround durable customize finding pharmaceutical steady reject motivation acknowledge spokesperson recipient

day14
remark cautious persuade overlook specification incorporate detour statistic sculpture carton broaden abstract outdated consistent premier shortage utilize improper pledge favorable overdue signature conform allowance resolve compliment relative informative coordinate faculty encounter occasionally

day15
interpret remote hospitality restrict seasonal precaution freight spacious stimulate advisory expertise consensus appoint pursue fluctuation transcribe partial abandon innovation numerous vacate combine enforce distinguish investigate circumstance negotiate confer capability recline integrity substitute