Commit df1d4e6a authored by Ricardo Cebada Fuentes's avatar Ricardo Cebada Fuentes 👦🏽

Actualización

parent 11cbbc85
{
"cells": [
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import pyaudio\n",
"import os\n",
"import struct\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from scipy.fftpack import fft\n",
"import time\n",
"from tkinter import TclError\n",
"\n",
"#Para disparar las gráficas en ventanas deparadas\n",
"%matplotlib tk\n",
"\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"#Se declaran las constantes para el objeto de pyaudio\n",
"CHUNK = 1024 * 2 #muetras por frame \n",
"FORMAT = pyaudio.paInt16 #formato de audio (bytes por muestra)\n",
"CHANNELS = 1 #Micrófono de un canal \n",
"RATE = 44100 #Frecuencia de muestreo "
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Escuchando...\n",
"Adquisición terminada\n",
"FPS promedio = 10 FPS\n"
]
}
],
"source": [
"#Se crea el una figura de matplotlib con dos ejes y tamaño 15x7\n",
"fig, (ax1, ax2) = plt.subplots(2, figsize=(15, 7))\n",
"\n",
"#Se crea una instancia de la clase pyaudio\n",
"p = pyaudio.PyAudio()\n",
"\n",
"#Se crea un objeto stream para adquirir datos del micrófono\n",
"stream = p.open(\n",
" format=FORMAT,\n",
" channels=CHANNELS,\n",
" rate=RATE,\n",
" input=True,\n",
" output=True,\n",
" frames_per_buffer=CHUNK\n",
")\n",
"\n",
"\n",
"#Se crea un arreglo de valores para graficar la señal \n",
"x = np.arange(0, 2 * CHUNK, 2) \n",
"#Arreglo para graficar el espectro\n",
"xf = np.linspace(0, RATE, CHUNK) \n",
"\n",
"#Se crea un objeto línea para el eje de la gráfica de la señal\n",
"line, = ax1.plot(x, np.random.rand(CHUNK), '-', lw=2)\n",
"\n",
"#objeto línea en escala logarítmica para la gráfica del espectro\n",
"line_fft, = ax2.semilogx(xf, np.random.rand(CHUNK), '-', lw=2)\n",
"\n",
"#Formato ejes de la gráfica de la señal\n",
"ax1.set_title('Señal de entrada')\n",
"ax1.set_xlabel('muestras')\n",
"ax1.set_ylabel('amplitud')\n",
"ax1.set_ylim(0, 255)\n",
"ax1.set_xlim(0, 2 * CHUNK)\n",
"plt.setp(ax1, xticks=[0, CHUNK, 2 * CHUNK], yticks=[0, 128, 255])\n",
"\n",
"\n",
"#Formato ejes para la gráfica del espectro\n",
"ax2.set_xlim(20, RATE / 2)\n",
"\n",
"print('Escuchando...')\n",
"\n",
"\n",
"frame_count = 0\n",
"start_time = time.time()\n",
"\n",
"#loop\n",
"\n",
"while True:\n",
" \n",
" #Leer micrófono (data:binarios)\n",
" data = stream.read(CHUNK) \n",
" \n",
" #Convertir data en enteros ...\n",
" data_int = struct.unpack(str(2 * CHUNK) + 'B', data)\n",
" \n",
" # create np array and offset by 128\n",
" data_np = np.array(data_int, dtype='b')[::2] + 128\n",
" \n",
" line.set_ydata(data_np)\n",
" \n",
" # calcular la fft de los datos enteros\n",
" yf = fft(data_int)\n",
" line_fft.set_ydata(np.abs(yf[0:CHUNK]) / (128 * CHUNK))\n",
" \n",
" # Actualizar la figura canvas\n",
" try:\n",
" fig.canvas.draw()\n",
" fig.canvas.flush_events()\n",
" frame_count += 1\n",
" \n",
" except TclError:\n",
" \n",
" # calcular el FPS promedio\n",
" frame_rate = frame_count / (time.time() - start_time)\n",
" \n",
" print('Adquisición terminada')\n",
" print('FPS promedio = {:.0f} FPS'.format(frame_rate))\n",
" break\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.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment