realtime FFT.ipynb 4.27 KB
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "    import numpy as np\n",
    "    import pylab\n",
    "    import matplotlib.pyplot as plt\n",
    "    from scipy.io import wavfile\n",
    "    import time\n",
    "    import sys\n",
    "    import seaborn as sns\n",
    "    import pyaudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "i=0\n",
    "f,ax = plt.subplots(2)\n",
    "\n",
    "# Prepare the Plotting Environment with random starting values\n",
    "x = np.arange(10000)\n",
    "y = np.random.randn(10000)\n",
    "\n",
    "# Plot 0 is for raw audio data\n",
    "li, = ax[0].plot(x, y)\n",
    "ax[0].set_xlim(0,1000)\n",
    "ax[0].set_ylim(-5000,5000)\n",
    "ax[0].set_title(\"Raw Audio Signal\")\n",
    "# Plot 1 is for the FFT of the audio\n",
    "li2, = ax[1].plot(x, y)\n",
    "ax[1].set_xlim(0,5000)\n",
    "ax[1].set_ylim(-100,100)\n",
    "ax[1].set_title(\"Fast Fourier Transform\")\n",
    "# Show the plot, but without blocking updates\n",
    "plt.pause(0.01)\n",
    "plt.tight_layout()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "FORMAT = pyaudio.paInt16 # We use 16bit format per sample\n",
    "CHANNELS = 1\n",
    "RATE = 44100\n",
    "CHUNK = 1024 # 1024bytes of data red from a buffer\n",
    "RECORD_SECONDS = 0.1\n",
    "WAVE_OUTPUT_FILENAME = \"file.wav\"\n",
    "\n",
    "audio = pyaudio.PyAudio()\n",
    "\n",
    "# start Recording\n",
    "stream = audio.open(format=FORMAT,\n",
    "                    channels=CHANNELS,\n",
    "                    rate=RATE,\n",
    "                    input=True)#,\n",
    "                    #frames_per_buffer=CHUNK)\n",
    "\n",
    "global keep_going\n",
    "keep_going = True\n",
    "\n",
    "def plot_data(in_data):\n",
    "    # get and convert the data to float\n",
    "    audio_data = np.fromstring(in_data, np.int16)\n",
    "    # Fast Fourier Transform, 10*log10(abs) is to scale it to dB\n",
    "    # and make sure it's not imaginary\n",
    "    dfft = 10.*np.log10(abs(np.fft.rfft(audio_data)))\n",
    "\n",
    "    # Force the new data into the plot, but without redrawing axes.\n",
    "    # If uses plt.draw(), axes are re-drawn every time\n",
    "    #print audio_data[0:10]\n",
    "    #print dfft[0:10]\n",
    "    #print\n",
    "    li.set_xdata(np.arange(len(audio_data)))\n",
    "    li.set_ydata(audio_data)\n",
    "    li2.set_xdata(np.arange(len(dfft))*10.)\n",
    "    li2.set_ydata(dfft)\n",
    "\n",
    "    # Show the updated plot, but without blocking\n",
    "    plt.pause(0.01)\n",
    "    if keep_going:\n",
    "        return True\n",
    "    else:\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# Open the connection and start streaming the data\n",
    "stream.start_stream()\n",
    "print (\"\\n+---------------------------------+\")\n",
    "print (\"| Press Ctrl+C to Break Recording |\")\n",
    "print (\"+---------------------------------+\\n\")\n",
    "\n",
    "# Loop so program doesn't end while the stream callback's\n",
    "# itself for new data\n",
    "while keep_going:\n",
    "    try:\n",
    "        plot_data(stream.read(CHUNK))\n",
    "    except KeyboardInterrupt:\n",
    "        keep_going=False\n",
    "    except:\n",
    "        pass\n",
    "\n",
    "# Close up shop (currently not used because KeyboardInterrupt\n",
    "# is the only way to close)\n",
    "stream.stop_stream()\n",
    "stream.close()\n",
    "\n",
    "audio.terminate()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}