山内セミナーⅠ(2021/06/30)

関連サイトと資料

サンプルプログラム(5)

list14.py
import wave
  
def chk_wave_file(fname):
    wav = wave.open(fname, 'r')
    nchannels, sampwidth, framerate, nframes, comptype, compname = wav.getparams()
    print('チャネル数:{0}'.format(nchannels))
    print('データサイズ:{0} [bytes]'.format(sampwidth))
    print('サンプリング周波数:{0} [Hz]'.format(framerate))
    print('サンプリング数:{0} [frames]'.format(nframes))

    time = nframes / framerate
    print('録音時間:{0} [sec]\n'.format(time))

    wav.close()
  
if __name__ == '__main__':
    targets = [ 'loop1.wav', 'sample1.wav' ]
    for fn in targets:
        print('[ {0} ]'.format(fn))
        chk_wave_file(fn)
    

list15.py
import wave
import numpy as np
import os
  
def extract(fname, t1, t2, savename):
    in_wav = wave.open(fname, 'r')
    nchannels, sampwidth, framerate, nframes, comptype, compname = in_wav.getparams()
    time = nframes / framerate
  
    if t1 >= 0 and t1 < time and t2 > t1 and t2 < time:
        start = int(t1*framerate)
        end = int(t2*framerate)

        data = in_wav.readframes(nframes)
        tmp_data = np.frombuffer(data, dtype='int16')
        x = tmp_data[(start * nchannels):(end * nchannels)]

        out_wav = wave.Wave_write(savename)
        nframes = x.size // nchannels
        out_wav.setparams((nchannels, sampwidth, framerate, nframes, comptype, compname))
        out_wav.writeframes(x)
        out_wav.close()
    else:
        print('指定した抜き出し時刻 t1, t2 の指定が不正です。')
  
    in_wav.close()
  
def createSavename(fn, s1):
    base, ext = os.path.splitext(fn)
    return base + s1 + ext
  
if __name__ == '__main__':
    targets = [ 'loop1.wav', 'sample1.wav' ]
    # 1秒から2秒までを抜き出す
    for fn in targets:
        sn = createSavename(fn, '_1_2')
        print('{0} -> {1}'.format(fn, sn))
        extract(fn, 1, 2, sn)
    

サンプルプログラム(6)

list16.py
import wave
import numpy as np
import os
  
def scale(fname, s, savename):
    in_wav = wave.open(fname, 'r')
    nchannels, sampwidth, framerate, nframes, comptype, compname = in_wav.getparams()
  
    data = in_wav.readframes(nframes)
    tmp_data = np.frombuffer(data, dtype='int16')
    x = np.copy(tmp_data).astype(dtype='float32')
    x *= s
    sat_x = np.clip(x, -32768, 32768).astype(np.int16)
  
    out_wav = wave.Wave_write(savename)
    out_wav.setparams((nchannels, sampwidth, framerate, nframes, comptype, compname))
    out_wav.writeframes(sat_x)
    out_wav.close()
    in_wav.close()
  
def createSavename(fn, s1):
    base, ext = os.path.splitext(fn)
    return base + s1 + ext
  
if __name__ == '__main__':
    targets = [ 'loop1.wav', 'sample1.wav' ]
    # ボリュームを1.2倍にする
    sc = 1.2
    for fn in targets:
        sn = createSavename(fn, '_vol12')
        print('{0} -> {1}'.format(fn, sn))
        scale(fn, sc, sn)
    

list17.py
import wave
import numpy as np
import os
  
def convert(fname, savename):
    in_wav = wave.open(fname, 'r')
    p = in_wav.getparams()
  
    if p.nchannels != 2:
        print('ステレオではありません!')
        exit()
  
    data = in_wav.readframes(p.nframes)
    tmp_data = np.frombuffer(data, dtype='int16')
    w = np.copy(tmp_data).astype(dtype='int32')
    w = w.reshape(w.size//2, 2)
  
    out_wav = wave.Wave_write(savename)
    l = list(p)
    l[0] = 1
    p_mono = tuple(l)
    out_wav.setparams(p_mono)
  
    x = w[:,0] - w[:,1]
    x = np.clip(x, -32768, 32768).astype(np.int16)

    out_wav.writeframes(x)
    out_wav.close()
    in_wav.close()
  
def createSavename(fn, s1):
    base, ext = os.path.splitext(fn)
    return base + s1 + ext
  
if __name__ == '__main__':
    targets = [ 'musicnation.wav', 'noise.wav' ]
    # ボーカルの声を消して、カラオケにします
    for fn in targets:
        sn = createSavename(fn, '_karaoke')
        print('{0} -> {1}'.format(fn, sn))
        convert(fn, sn)
    

サンプルプログラム(7)

list18.py
import wave
import numpy as np
import os
  
def delay(fname, t, savename):
    in_wav = wave.open(fname, 'r')
    p = in_wav.getparams()
  
    data = in_wav.readframes(p.nframes)
    data = np.frombuffer(data, dtype='int16') / 32768.0
  
    delay_frames = int(p.framerate * t * p.nchannels)
    data *= 0.5
    data[delay_frames:(p.nframes * p.nchannels)] += data[0:(p.nframes * p.nchannels - delay_frames)]
  
    data *= 32768
    d = data.astype(np.int16)
  
    out_wav = wave.Wave_write(savename)
    out_wav.setparams(p)
    out_wav.writeframes(d)
    out_wav.close()
    in_wav.close()
  
def createSavename(fn, s1):
    base, ext = os.path.splitext(fn)
    return base + s1 + ext
  
if __name__ == '__main__':
    targets = [ 'loop1.wav', 'sample1.wav' ]
    dt = 0.5
    for fn in targets:
        sn = createSavename(fn, '_delay05')
        print('{0} -> {1}'.format(fn, sn))
        delay(fn, dt, sn)
    

list19.py
import wave
import numpy as np
import os
  
def reverb(fname, a_rate, taps, t, savename):
    in_wav = wave.open(fname, 'r')
    p = in_wav.getparams()
  
    data = in_wav.readframes(p.nframes)
    data = np.frombuffer(data, dtype='int16') / 32768.0
  
    delay_frames = int(p.framerate * t)
  
    newdata = data.astype(np.float32)
    for tap_idx in range(1, taps+1):
        start = int(tap_idx * delay_frames * p.nchannels)
        end = p.framerate * p.nchannels
        if start >= end:
            break
        newdata[start:end] += (a_rate ** tap_idx) * data[0:(end-start)]
  
    newdata *= 32768
    d = np.clip(newdata, -32768, 32767).astype(np.int16)
  
    out_wav = wave.Wave_write(savename)
    out_wav.setparams(p)
    out_wav.writeframes(d)
    out_wav.close()
    in_wav.close()
  
def createSavename(fn, s1):
    base, ext = os.path.splitext(fn)
    return base + s1 + ext
  
if __name__ == '__main__':
    targets = [ 'loop1.wav', 'sample1.wav' ]
    atten_rate = 0.6
    taps = 6
    dt = 0.1
    for fn in targets:
        sn = createSavename(fn, '_reverb')
        print('{0} -> {1}'.format(fn, sn))
        reverb(fn, atten_rate, taps, dt, sn)
    

サンプルプログラム(8)

list20.py
import matplotlib.pyplot as plt
  
if __name__ == '__main__':
    amp = [20, 25, 38, 45, 50, 45, 38, 20, 25, 50]
    plt.plot(amp)
    plt.show()
    

list21.py
import matplotlib.pyplot as plt
  
if __name__ == '__main__':
    amp = [20, 25, 38, 45, 50, 45, 38, 20, 25, 50]
    time = [.0, .1, .2, .3, .4, .5, .6, .7, .8, .9]
    plt.plot(time, amp)
    plt.show()
    

list22.py
import matplotlib.pyplot as plt
  
if __name__ == '__main__':
    amp = [20, 25, 38, 45, 50, 45, 38, 20, 25, 50]
    time = [.0, .1, .2, .3, .4, .5, .6, .7, .8, .9]
  
    plt.plot(time, amp, label='graph')
    plt.title('title')
    plt.xlabel('time[sec]')
    plt.ylabel('amplitude')
  
    plt.legend()
    plt.show()
    

list23.py
import matplotlib.pyplot as plt
  
if __name__ == '__main__':
    amp = [20, 25, 38, 45, 50, 45, 38, 20, 25, 50]
    time = [.0, .1, .2, .3, .4, .5, .6, .7, .8, .9]
  
    plt.plot(time, amp, label='graph')
    plt.title('title')
    plt.xlabel('time[sec]')
    plt.ylabel('amplitude')
    plt.xlim([0, .6])
    plt.ylim([25, 80])
  
    plt.legend()
    plt.show()
    

list24.py
import matplotlib.pyplot as plt
  
if __name__ == '__main__':
    amp1 = [20, 25, 38, 45, 50, 45, 38, 20, 25, 50]
    amp2 = [45, 38, 20, 25, 45, 20, 25, 38, 40, 45]
  
    plt.plot(amp1)
    plt.plot(amp2)
    plt.show()
    

list25.py
import numpy as np
import matplotlib.pyplot as plt
  
if __name__ == '__main__':
    x = np.linspace(0, 2*np.pi, 100)
    y = np.sin(x)
  
    plt.plot(x, y)
    plt.show()
    

list26.py
import numpy as np
import matplotlib.pyplot as plt
  
if __name__ == '__main__':
    x = np.linspace(0, 2*np.pi, 100)
    sin_y = np.sin(x)
    cos_y = np.cos(x)
  
    plt.plot(x, sin_y, label='sin', color='red')
    plt.plot(x, cos_y, label='cos', color='blue')
    plt.title('sin/cos wave')
    plt.xlabel('X-value')
    plt.ylabel('Y-value')
  
    plt.legend()
    plt.show()
    

list27.py
import numpy as np
import matplotlib.pyplot as plt
  
if __name__ == '__main__':
    x = np.linspace(0, 2*np.pi, 100)
    sin_y = np.sin(x)
    cos_y = np.cos(x)
  
    plt.plot(x, sin_y, label='sin', color='red')
    plt.plot(x, cos_y, label='cos', color='blue')
    plt.title('sin/cos wave')
    plt.xlabel('X-value')
    plt.ylabel('Y-value')
    plt.grid(True)
  
    plt.legend()
    plt.show()
    

list28.py
import numpy as np
import matplotlib.pyplot as plt
  
if __name__ == '__main__':
    x = np.linspace(0, 2*np.pi, 100)
    sin_y = np.sin(x)
    cos_y = np.cos(x) * 2
  
    fig, axs = plt.subplots(2, 1, sharex=True, sharey=True)
    sin_cos = [sin_y, cos_y]
    ylabel = ['left', 'right']
    xylabel = ['sin', 'cos']
    xycolor = ['red', 'blue']
  
    for i in range(2):
        axs[i].plot(sin_cos[i], label=xylabel[i], color=xycolor[i])
        axs[i].grid(True)
        axs[i].set_ylabel(ylabel[i])
        axs[i].legend()
      
    plt.xlabel('time')
    plt.show()