Created
December 30, 2015 16:20
-
-
Save wakusei-meron-/c8ebe18c5f1b26f173b4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#coding: utf-8 | |
from scipy import sin | |
from math import pi | |
import numpy as np | |
import pylab as pl | |
import struct | |
import time | |
def createSinWave(a, f, sampling_rate, time_s): | |
"""a: 振幅, f:周波数, sampling_rate: サンプリング周波数, time_s:トータル時間[秒] | |
上記の条件でsin波を生成""" | |
dt = 1. / sampling_rate # サンプリングの時間間隔[s] | |
count = np.arange(time_s / dt) # 指定時間内のデータ数 | |
data = [] | |
for i in count: | |
# sin(2π * f * dt) | |
p = a * sin(2 * pi * f * (i * dt)) | |
# 振幅 a > |1|の時はクリッピング(量子化の最大値に合わせる) | |
if p > 1: p = 1 | |
if p < -1: p = -1 | |
data.append(p) | |
# 16bitで量子化 | |
data = [int(x * pow(2, 15 - 1)) for x in data] | |
# pl.plot(dt * n, data) | |
# pl.show() | |
# バイナリに変換(cのデータ型に変換 h → short) | |
data = struct.pack("h" * len(data), *data) | |
return data | |
def play(data, sampling_rate): | |
"""data: 16bitで量子化された振幅配列, sampling_rate: サンプリング周波数 | |
dataを再生する""" | |
import pyaudio | |
# pyaudioとストリームの初期化 | |
p = pyaudio.PyAudio() | |
stream = p.open( | |
format = pyaudio.paInt16, | |
channels = 1, | |
rate = int(sampling_rate), | |
output = True | |
) | |
# ストリームに書き込んで、音を鳴らす | |
stream.write(data) | |
# 参照したブログだと部分ごとにデータを取り出して、音を鳴らす | |
# http://aidiary.hatenablog.com/entry/20110607/1307449007 | |
# チャンク単位でストリームに出力して音声再生 | |
# chunk = 1024 | |
# sp = 0 | |
# buffer = data[sp:sp+chunk] | |
# print len(buffer) | |
# while len(buffer) != 0: | |
# stream.write(buffer) | |
# sp += chunk | |
# buffer = data[sp: sp+chunk] | |
# 終了処理 | |
stream.close() | |
p.terminate() | |
def main(): | |
amp = 1 # 振幅 | |
fs = 262 # ドの周波数[Hz] | |
sampling_rate = 44.1e3 # CDの標準周波数 | |
time_s = 1 # 鳴らす時間[s] | |
data = createSinWave(amp, fs, sampling_rate, time_s) | |
play(data, sampling_rate) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment