Skip to content

Instantly share code, notes, and snippets.

@takatakamanbou
Last active June 2, 2020 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takatakamanbou/004bb005dc1aa400a57917a9f82c691a to your computer and use it in GitHub Desktop.
Save takatakamanbou/004bb005dc1aa400a57917a9f82c691a to your computer and use it in GitHub Desktop.
PIP2020-08-note2.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "PIP2020-08-note2.ipynb",
"provenance": [],
"collapsed_sections": [],
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/takatakamanbou/004bb005dc1aa400a57917a9f82c691a/pip2020-08-note2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NI3mY1FGZWgV",
"colab_type": "text"
},
"source": [
"# 2020年度パターン情報処理第8回講義資料その2\n",
"\n",
"この科目のウェブサイトへ https://www-tlab.math.ryukoku.ac.jp/wiki/?PIP/2020\n",
"\n",
"![hoge](https://www-tlab.math.ryukoku.ac.jp/~takataka/course/PIP/PIP-logo-96x96.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ffaGVK2o5VWe",
"colab_type": "text"
},
"source": [
"## はじめに"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0IpujRN_Wuib",
"colab_type": "text"
},
"source": [
"### これは何?\n",
"\n",
"これは,Google Colaboratory(以下 Google Colab) という,Google が提供しているサービスを利用して作成した資料です.Notebook と呼びます.クラウド上に仮想的に構築された Linux マシン上で Python のプログラムを実行することができます."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QRNjWashW4pr",
"colab_type": "text"
},
"source": [
"### Notebook の動かし方\n",
"\n",
"この Notebook では,上の方のセルで作った変数や関数を後のセルで使うことがあります.そのため,上の方のセルを実行せずに下の方を実行すると,エラーになることがあります.上から順に実行していきましょう.\n",
"\n",
"また,メニューの「ランタイム」から,「すべてのセルを実行」したりすることも可能です."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1jfSXIY6VNxP",
"colab_type": "text"
},
"source": [
"## 準備\n",
"\n",
"以下のセルは,プログラムを実行するための準備を行うためのものです.このセルを実行してから,先へ進みましょう."
]
},
{
"cell_type": "code",
"metadata": {
"id": "IFYQk7ONZENz",
"colab_type": "code",
"colab": {}
},
"source": [
"# 科学技術計算のライブラリ NumPy のモジュールを np という名前で使えるようにする\n",
"import numpy as np\n",
"# 科学技術計算のライブラリ SciPy の中の WAVE ファイルを扱うモジュール を wavfile という名前で使えるようにする\n",
"import scipy.io.wavfile as wavfile\n",
"# グラフを描くためのライブラリ matplotlib の pyplot を plt という名前でインポート\n",
"import matplotlib.pyplot as plt\n",
"\n",
"import os"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "807R4hQI5oH9",
"colab_type": "code",
"colab": {}
},
"source": [
"# WAVE ファイルを読み込む関数\n",
"#\n",
"def readWAVE(filename):\n",
" \n",
" framerate, data = wavfile.read(filename)\n",
"\n",
" # チャンネル数とフレーム数(データ点の数)を求める\n",
" if data.ndim == 1:\n",
" nchannels = 1\n",
" else:\n",
" nchannels = data.shape[1]\n",
" nframes = data.shape[0]\n",
" \n",
" print('filename = ', filename)\n",
" print('nchannels = ', nchannels) # チャンネル数\n",
" print('framerate = ', framerate) # 標本化周波数\n",
" print('nframes = ', nframes) # フレーム数\n",
" print('duration = {0:.2f}[sec]'.format(nframes / framerate)) # 長さ(秒単位)\n",
" print('dtype = ', data.dtype) # データ型(量子化ビット数に対応)\n",
"\n",
" assert data.dtype == 'uint8' or data.dtype == 'int16' or data.dtype == 'int32' or data.dtype == 'float32'\n",
" \n",
" # 最初の10秒分だけ取り出す(元がそれより短ければそのまま)\n",
" nframesNew = min(framerate * 10, nframes) \n",
" if nchannels == 1:\n",
" dataNew = data[:nframesNew]\n",
" else:\n",
" # 多チャンネル信号なら0番目と1番目の平均値を取り出す\n",
" if data.dtype == 'float32': # 浮動小数点数のときは [0, 1] の値なので普通に足して2で割る\n",
" dataNew = (data[:nframesNew, 0] + data[:nframesNew, 1])/2\n",
" else: # 整数型のときはオーバーフローする可能性があるので,いったん64bit整数にしてから\n",
" data64 = (data[:nframesNew, 0].astype(np.int64) + data[:nframesNew, 1].astype(np.int64))//2\n",
" dataNew = data64.astype(data.dtype)\n",
" \n",
" return framerate, dataNew\n",
"\n",
"\n",
"# WAVE ファイルを書き込む関数(モノラル限定)\n",
"#\n",
"def writeWAVE(filename, framerate, data):\n",
"\n",
" assert data.ndim == 1\n",
"\n",
" wavfile.write(filename, framerate, data)\n"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "82S39H2VB8oX",
"colab_type": "text"
},
"source": [
"## 正弦波のスペクトル"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "39pG5akMPrP8",
"colab_type": "text"
},
"source": [
"### 正弦波の信号を作る\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "w9YIPxtAqXsN",
"colab_type": "code",
"colab": {}
},
"source": [
"### 設定いろいろ\n",
"#\n",
"sampfreq = 8000 # 標本化周波数\n",
"valmax = 2 ** 15 - 1 # 16ビットで量子化 => 値の最大\n",
"duration = 2 # 信号の持続時間\n",
"\n",
"# 時間軸\n",
"t = np.arange(0, duration, 1.0/sampfreq)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "e0KK4HPb6X4T",
"colab_type": "text"
},
"source": [
"sin500(正弦波その1): 周波数 500 Hz "
]
},
{
"cell_type": "code",
"metadata": {
"id": "Lj7BiA-QB-5H",
"colab_type": "code",
"colab": {}
},
"source": [
"### 正弦波その1\n",
"#\n",
"sigfreq = 500 # 周波数: 500Hz\n",
"amp = valmax*0.5 # 振幅: 最大の 0.5 倍\n",
"raw = amp * np.sin(2*np.pi*sigfreq*t) # 信号値を作成\n",
"sin500 = raw.astype(np.int16) # それを16ビット整数値に変換\n",
"\n",
"writeWAVE('sin500.wav', sampfreq, sin500)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "6s4TK05p6dMy",
"colab_type": "text"
},
"source": [
"sin200(正弦波その2): 周波数200Hz,振幅はsin500の半分"
]
},
{
"cell_type": "code",
"metadata": {
"id": "1R4gsGcOFahy",
"colab_type": "code",
"colab": {}
},
"source": [
"### 正弦波その2\n",
"#\n",
"sigfreq = 200 # 周波数: 200Hz\n",
"amp = valmax * 0.25 # 振幅: 最大の 0.25 倍\n",
"raw = amp * np.sin(2*np.pi*sigfreq*t) # 信号値を作成\n",
"sin200 = raw.astype(np.int16) # それを16ビット整数値に変換\n",
"\n",
"writeWAVE('sin200a0.5.wav', sampfreq, sin200)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "35atLHsK6iOI",
"colab_type": "text"
},
"source": [
"signal(正弦波その1+その2): 二つの信号を足し合わせたもの"
]
},
{
"cell_type": "code",
"metadata": {
"id": "8LBxlrOIHGT9",
"colab_type": "code",
"colab": {}
},
"source": [
"### 二つの正弦波を足した信号\n",
"#\n",
"signal = sin500 + sin200\n",
"\n",
"writeWAVE('sin500+sin200a0.5.wav', sampfreq, signal)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "uPwko5FB95TG",
"colab_type": "text"
},
"source": [
"以下のセルのコメントの指示にしたがって修正してから実行すると,上記で作った3つの音のファイル(WAVE形式,拡張子 `.wav`)をダウンロードできます.自分のPCで鳴らしてみよう."
]
},
{
"cell_type": "code",
"metadata": {
"id": "7XdEkvRH935z",
"colab_type": "code",
"colab": {}
},
"source": [
"# ファイル一覧\n",
"! ls -l\n",
"\n",
"# ファイルをダウンロード\n",
"from google.colab import files\n",
"if 1 == 0: # ←の 0 を 1 に修正\n",
" files.download('sin500.wav')\n",
" files.download('sin200a0.5.wav')\n",
" files.download('sin500+sin200a0.5.wav')"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "VWPn60Q_5vJR",
"colab_type": "text"
},
"source": [
"### 数値をそのまま眺めてみる"
]
},
{
"cell_type": "code",
"metadata": {
"id": "-12jHZtBErBR",
"colab_type": "code",
"colab": {}
},
"source": [
"### それぞれの値を表示してみる.最初の32個\n",
"#\n",
"nt = 32\n",
"for i in range(nt):\n",
" print(\"{:.6f} {:7d} {:7d} {:7d}\".format(t[i], sin500[i], sin200[i], signal[i]))"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "MNP_S-6F6C9D",
"colab_type": "text"
},
"source": [
"### 波形そのもののグラフを描いてみる"
]
},
{
"cell_type": "code",
"metadata": {
"id": "vqMvTsOvFWYZ",
"colab_type": "code",
"colab": {}
},
"source": [
"### 波形そのもののグラフを描いてみる\n",
"#\n",
"fig, ax = plt.subplots(3, facecolor=\"white\", figsize=(8, 12))\n",
"ax[0].plot(t[:nt], signal[:nt], \".\", color=\"red\", label=\"signal\")\n",
"ax[0].set_xlim(0, t[nt-1])\n",
"ax[0].set_ylim(-valmax, valmax)\n",
"ax[0].legend()\n",
"ax[1].plot(t[:nt], sin500[:nt], \".\", color=\"green\", label=\"sin500\")\n",
"ax[1].set_xlim(0, t[nt-1])\n",
"ax[1].set_ylim(-valmax, valmax)\n",
"ax[1].legend()\n",
"ax[2].plot(t[:nt], sin200[:nt], \".\", color=\"blue\", label=\"sin200\")\n",
"ax[2].set_xlim(0, t[nt-1])\n",
"ax[2].set_ylim(-valmax, valmax)\n",
"ax[2].legend()\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "LLE5f7GQ7BA5",
"colab_type": "text"
},
"source": [
"### 振幅スペクトルを描いてみる"
]
},
{
"cell_type": "code",
"metadata": {
"id": "6ruaoHpPFX0R",
"colab_type": "code",
"colab": {}
},
"source": [
"### フーリエ変換して振幅スペクトルを求め,グラフに描く\n",
"#\n",
"N = signal.shape[0]\n",
"freq = np.arange(N) * sampfreq / N # 横軸の値.単位は Hz\n",
"fig, ax = plt.subplots(3, facecolor=\"white\", figsize=(8, 12))\n",
"C = np.fft.fft(signal)/N\n",
"spec_amp = np.abs(C)\n",
"ax[0].plot(freq, spec_amp, \"-\", color=\"red\", label=\"signal\")\n",
"ax[0].set_xlim(0, 2000)\n",
"ax[0].set_ylim(0, 10000)\n",
"ax[0].legend()\n",
"C = np.fft.fft(sin500)/N\n",
"spec_amp = np.abs(C)\n",
"ax[1].plot(freq, spec_amp, \"-\", color=\"green\", label=\"sin500\")\n",
"ax[1].set_xlim(0, 2000)\n",
"ax[1].set_ylim(0, 10000)\n",
"ax[1].legend()\n",
"C = np.fft.fft(sin200)/N\n",
"spec_amp = np.abs(C)\n",
"ax[2].plot(freq, spec_amp, \"-\", color=\"blue\", label=\"sin200\")\n",
"ax[2].set_xlim(0, 2000)\n",
"ax[2].set_ylim(0, 10000)\n",
"ax[2].legend()\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "ZQes7NbF7fkG",
"colab_type": "text"
},
"source": [
"## ギターの音のスペクトル"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_xAHHlUI7lF8",
"colab_type": "text"
},
"source": [
"### データの入手"
]
},
{
"cell_type": "code",
"metadata": {
"id": "HVXeeHuU7hfQ",
"colab_type": "code",
"colab": {}
},
"source": [
"# WAVE ファイルをダウンロード\n",
"! wget -nc https://www-tlab.math.ryukoku.ac.jp/~takataka/course/PIP/Sound-Guitar1-C.wav\n",
"! wget -nc https://www-tlab.math.ryukoku.ac.jp/~takataka/course/PIP/Sound-Guitar2-E.wav\n",
"! ls -l\n",
"\n",
"fnC = 'Sound-Guitar1-C.wav'\n",
"fnE = 'Sound-Guitar2-E.wav'\n",
"\n",
"if not os.path.exists(fnC):\n",
" print(f'{fnC}のダウンロードがうまくできていないようです')\n",
"if not os.path.exists(fnE):\n",
" print(f'{fnE}のダウンロードがうまくできていないようです')"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "AzUFWdnt8D4n",
"colab_type": "code",
"colab": {}
},
"source": [
"# WAVEファイルの内容を読み込む\n",
"sampfreq, signalC = readWAVE(fnC)\n",
"sampfreq2, signalE = readWAVE(fnE)\n",
"\n",
"assert sampfreq == sampfreq2 and signalC.shape[0] == signalE.shape[0]\n",
"N = signalC.shape[0]\n",
"valmax = 2 ** 8 - 1 # 8ビット(符号なし)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "Psti_PFQAQse"
},
"source": [
"以下のセルのコメントの指示にしたがって修正してから実行すると,上記で使っている2つの音のファイル(WAVE形式,拡張子 `.wav`)をダウンロードできます.自分のPCで鳴らしてみよう."
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "GkRSW4RlAQsg",
"colab": {}
},
"source": [
"# ファイル一覧\n",
"! ls -l\n",
"\n",
"# ファイルをダウンロード\n",
"from google.colab import files\n",
"if 1 == 0: # ←の 0 を 1 に修正\n",
" files.download(fnC)\n",
" files.download(fnE)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "xwdGIAtj9OjD",
"colab_type": "text"
},
"source": [
"### 波形そのもののグラフを描いてみる"
]
},
{
"cell_type": "code",
"metadata": {
"id": "54a-XVAG9DPH",
"colab_type": "code",
"colab": {}
},
"source": [
"# 時間軸\n",
"t = np.arange(0, N/sampfreq, 1.0/sampfreq)\n",
"\n",
"### 波形そのもののグラフを描いてみる\n",
"#\n",
"ns, ne = 0, sampfreq # 最初の1秒間\n",
"fig, ax = plt.subplots(2, facecolor=\"white\", figsize=(8, 6))\n",
"ax[0].plot(t[ns:ne], signalC[ns:ne], \".\", color=\"red\", label=\"guitar C\")\n",
"ax[0].set_xlim(t[ns], t[ne])\n",
"ax[0].set_ylim(0, valmax)\n",
"ax[0].legend()\n",
"ax[1].plot(t[ns:ne], signalE[ns:ne], \".\", color=\"blue\", label=\"guitar E\")\n",
"ax[1].set_xlim(t[ns], t[ne])\n",
"ax[1].set_ylim(0, valmax)\n",
"ax[1].legend()\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "z6uP9anw9S8a",
"colab_type": "code",
"colab": {}
},
"source": [
"### 波形そのもののグラフを描いてみる\n",
"#\n",
"ns, ne = int(0.2*sampfreq), int(0.21*sampfreq) # [0.2, 0.21) の 0.01 秒分\n",
"fig, ax = plt.subplots(2, facecolor=\"white\", figsize=(8, 6))\n",
"ax[0].plot(t[ns:ne], signalC[ns:ne], \".\", color=\"red\", label=\"guitar C\")\n",
"ax[0].set_xlim(t[ns], t[ne])\n",
"ax[0].set_ylim(0, valmax)\n",
"ax[0].legend()\n",
"ax[1].plot(t[ns:ne], signalE[ns:ne], \".\", color=\"blue\", label=\"guitar E\")\n",
"ax[1].set_xlim(t[ns], t[ne])\n",
"ax[1].set_ylim(0, valmax)\n",
"ax[1].legend()\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "e1f6zK7-9jL2",
"colab_type": "text"
},
"source": [
"### 振幅スペクトルを描いてみる"
]
},
{
"cell_type": "code",
"metadata": {
"id": "Wu9Aq4Pi9ffA",
"colab_type": "code",
"colab": {}
},
"source": [
"### フーリエ変換して振幅スペクトルを求め,グラフに描く\n",
"#\n",
"freq = np.arange(N) * sampfreq / N # 横軸の値.単位は Hz\n",
"fig, ax = plt.subplots(2, facecolor=\"white\", figsize=(8, 6))\n",
"C = np.fft.fft(signalC)/N\n",
"spec_amp = np.abs(C)\n",
"ax[0].plot(freq, spec_amp, \"-\", color=\"red\", label=\"guitar C\")\n",
"ax[0].set_xlim(0, 4000)\n",
"ax[0].set_ylim(0, 8)\n",
"ax[0].legend()\n",
"C = np.fft.fft(signalE)/N\n",
"spec_amp = np.abs(C)\n",
"ax[1].plot(freq, spec_amp, \"-\", color=\"blue\", label=\"guitar E\")\n",
"ax[1].set_xlim(0, 4000)\n",
"ax[1].set_ylim(0, 8)\n",
"ax[1].legend()\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "d9MsZDVBqF_Z",
"colab_type": "text"
},
"source": [
"## もふもふの音のスペクトル"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "r6xDlFfcqR9M"
},
"source": [
"### データの入手"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "aHxP1ppLqR9N",
"colab": {}
},
"source": [
"# WAVE ファイルをダウンロード\n",
"#\n",
"### こちらのサイトの素材を利用させてもらってます http://www.ne.jp/asahi/music/myuu/wave/wave.htm\n",
"\n",
"! wget -nc http://www.ne.jp/asahi/music/myuu/wave/cat1.wav\n",
"! wget -nc http://www.ne.jp/asahi/music/myuu/wave/cat2.wav\n",
"! cp cat1.wav mofumofu2.wav\n",
"! cp cat2.wav mofumofu1.wav\n",
"! ls -l\n",
"fn1 = 'mofumofu1.wav'\n",
"fn2 = 'mofumofu2.wav'\n",
"\n",
"if not os.path.exists(fn1):\n",
" print(f'{fn1}のダウンロードがうまくできていないようです')\n",
"if not os.path.exists(fn2):\n",
" print(f'{fn2}のダウンロードがうまくできていないようです')"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "yCzndUjYqR9S",
"colab": {}
},
"source": [
"# WAVEファイルの内容を読み込む\n",
"sampfreq1, signal1 = readWAVE(fn1)\n",
"sampfreq2, signal2 = readWAVE(fn2)\n",
"\n",
"assert sampfreq1 == sampfreq2\n",
"N = min(signal1.shape[0], signal2.shape[0])\n",
"signal1 = signal1[:N]\n",
"signal2 = signal2[:N]\n",
"assert signal1.shape[0] == signal2.shape[0]\n",
"valmax = 2 ** 15 - 1 # 16ビット(符号あり)\n",
"\n",
"print(np.min(signal1), np.max(signal1))\n",
"print(np.min(signal2), np.max(signal2))"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "9_he9-nkqR9V"
},
"source": [
"以下のセルのコメントの指示にしたがって修正してから実行すると,上記で使っている2つの音のファイル(WAVE形式,拡張子 `.wav`)をダウンロードできます.自分のPCで鳴らしてみよう."
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "G-mtyL_dqR9V",
"colab": {}
},
"source": [
"# ファイル一覧\n",
"! ls -l\n",
"\n",
"# ファイルをダウンロード\n",
"from google.colab import files\n",
"if 1 == 0: # ←の 0 を 1 に修正\n",
" files.download(fn1)\n",
" files.download(fn2)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "cmN5IzsDs3k6"
},
"source": [
"### 振幅スペクトルを描いてみる"
]
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "hTPNzVets3k7",
"colab": {}
},
"source": [
"### フーリエ変換して振幅スペクトルを求め,グラフに描く\n",
"#\n",
"freq = np.arange(N) * sampfreq1 / N # 横軸の値.単位は Hz\n",
"fig, ax = plt.subplots(2, facecolor=\"white\", figsize=(8, 6))\n",
"C = np.fft.fft(signal1)/N\n",
"spec_amp = np.abs(C)\n",
"ax[0].plot(freq, spec_amp, \"-\", color=\"red\", label=\"mofumofu1\")\n",
"ax[0].set_xlim(0, 8000)\n",
"ax[0].set_ylim(0, 400)\n",
"ax[0].legend()\n",
"C = np.fft.fft(signal2)/N\n",
"spec_amp = np.abs(C)\n",
"ax[1].plot(freq, spec_amp, \"-\", color=\"blue\", label=\"mofumofu2\")\n",
"ax[1].set_xlim(0, 8000)\n",
"ax[1].set_ylim(0, 400)\n",
"ax[1].legend()\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "K7p_m2v5PpER",
"colab_type": "text"
},
"source": [
"## おまけ\n",
"\n",
"ここから下は,おまけです.やること必須の宿題ではありません.やったら棒茄子?\n",
"\n",
"自分の好きな音のデータの振幅スペクトルを描いてみよう."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pQs437grOCEi",
"colab_type": "text"
},
"source": [
"WAVE形式のファイルをアップロードしましょう.\n",
"\n",
"日本語や空白,記号などの入ったファイル名はうまく扱えないことがあるので,適当に名前を付け替えてからアップロードするのがよいかも."
]
},
{
"cell_type": "code",
"metadata": {
"id": "bDZFxmL6wmP4",
"colab_type": "code",
"colab": {}
},
"source": [
"# ファイルをアップロード \n",
"from google.colab import files\n",
"uploaded = files.upload() # この行をコメントはずして実行すると,ファイルをアップロードできます\n",
"\n",
"# ファイル名を一覧\n",
"!ls -l"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "ITlpsiiaOTXV",
"colab_type": "text"
},
"source": [
"WAVEファイルを読み込みます.上記のセルを実行してからファイルを選択するまでに時間がかかると,ファイルが読み込まれずに進んでしまいます(先に ls コマンドの実行結果が出る,当然そこに所望のファイルはない).その場合は,セルの実行をやり直しましょう.\n",
"\n",
"関数 readWAVE がエラーを出す場合は,扱えないファイル形式なのかもしれません.また,巨大なデータを扱うはめになるのを避けるため,readWAVE は最初の10秒以内の分しか取り出しません.ただし,いったんデータを全部メモリに読み込むので,大きいデータだとエラーになるかも."
]
},
{
"cell_type": "code",
"metadata": {
"id": "L3QK6OsDMGTL",
"colab_type": "code",
"colab": {}
},
"source": [
"# ファイル名を指定\n",
"fn = \"mofumofu1.wav\" # ここをアップロードしたファイル名に修正\n",
"\n",
"# WAVEファイルの内容を読み込む\n",
"if not os.path.exists(fn):\n",
" print(f'{fn}が見つかりません')\n",
"else:\n",
" sampfreq, signal = readWAVE(fn)"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "BE0ZSiFYMlD1",
"colab_type": "code",
"colab": {}
},
"source": [
"### フーリエ変換して振幅スペクトルを求め,グラフに描く\n",
"#\n",
"N = signal.shape[0]\n",
"freq = np.arange(N) * sampfreq / N # 横軸の値.単位は Hz\n",
"fig, ax = plt.subplots(facecolor=\"white\", figsize=(8, 6))\n",
"C = np.fft.fft(signal)/N\n",
"spec_amp = np.abs(C)\n",
"\n",
"ax.plot(freq, spec_amp, \"-\", color=\"red\")\n",
"\n",
"# 横軸は標本化周波数の半分の周波数まで描く.縦軸は自動設定.\n",
"# => グラフが見づらい場合は,以下のコメントを参考に手動で値を設定するとよい\n",
"ax.set_xlim(0, sampfreq/2)\n",
"#ax.set_xlim(0, 4000) # 横軸の範囲を手動設定する例: 0 から 4000Hz まで\n",
"#ax.set_ylim(0, 400) # 縦軸の範囲を手動設定する例: 0 から 400 まで\n",
"\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "DetVKwH6PRKu",
"colab_type": "text"
},
"source": [
"上記のスペクトルの画像と,どんな音のデータなのか,スペクトルを見てのかんたんな考察等を Teams チャットで送ってください."
]
},
{
"cell_type": "code",
"metadata": {
"id": "bMLRwYhEkDQ8",
"colab_type": "code",
"colab": {}
},
"source": [
""
],
"execution_count": 0,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment