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

Algunos cambios a Principal

parent b7f8af7f
import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import struct
import pyaudio
import os
import struct
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft
import sys
import time
class AudioStream(object):
def __init__(self):
# pyqtgraph stuff
pg.setConfigOptions(antialias=True)
self.traces = dict()
self.app = QtGui.QApplication(sys.argv)
self.win = pg.GraphicsWindow(title='Spectrum Analyzer')
self.win.setWindowTitle('Spectrum Analyzer')
self.win.setGeometry(5, 115, 1910, 1070)
wf_xlabels = [(0, '0'), (2048, '2048'), (4096, '4096')]
wf_xaxis = pg.AxisItem(orientation='bottom')
wf_xaxis.setTicks([wf_xlabels])
wf_ylabels = [(0, '0'), (127, '128'), (255, '255')]
wf_yaxis = pg.AxisItem(orientation='left')
wf_yaxis.setTicks([wf_ylabels])
sp_xlabels = [
(np.log10(10), '10'), (np.log10(100), '100'),
(np.log10(1000), '1000'), (np.log10(22050), '22050')
]
sp_xaxis = pg.AxisItem(orientation='bottom')
sp_xaxis.setTicks([sp_xlabels])
self.waveform = self.win.addPlot(
title='WAVEFORM', row=1, col=1, axisItems={'bottom': wf_xaxis, 'left': wf_yaxis},
)
self.spectrum = self.win.addPlot(
title='SPECTRUM', row=2, col=1, axisItems={'bottom': sp_xaxis},
)
# pyaudio stuff
self.FORMAT = pyaudio.paInt16
self.CHANNELS = 1
self.RATE = 44100
self.CHUNK = 1024 * 2
self.p = pyaudio.PyAudio()
self.stream = self.p.open(
format=self.FORMAT,
channels=self.CHANNELS,
rate=self.RATE,
input=True,
output=True,
frames_per_buffer=self.CHUNK,
)
# waveform and spectrum x points
self.x = np.arange(0, 2 * self.CHUNK, 2)
self.f = np.linspace(0, self.RATE / 2, self.CHUNK / 2)
def start(self):
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
def set_plotdata(self, name, data_x, data_y):
if name in self.traces:
self.traces[name].setData(data_x, data_y)
else:
if name == 'waveform':
self.traces[name] = self.waveform.plot(pen='c', width=3)
self.waveform.setYRange(0, 255, padding=0)
self.waveform.setXRange(0, 2 * self.CHUNK, padding=0.005)
if name == 'spectrum':
self.traces[name] = self.spectrum.plot(pen='m', width=3)
self.spectrum.setLogMode(x=True, y=True)
self.spectrum.setYRange(-4, 0, padding=0)
self.spectrum.setXRange(
np.log10(20), np.log10(self.RATE / 2), padding=0.005)
def update(self):
wf_data = self.stream.read(self.CHUNK)
wf_data = struct.unpack(str(2 * self.CHUNK) + 'B', wf_data)
wf_data = np.array(wf_data, dtype='b')[::2] + 128
self.set_plotdata(name='waveform', data_x=self.x, data_y=wf_data,)
sp_data = fft(np.array(wf_data, dtype='int8') - 128)
sp_data = np.abs(sp_data[0:int(self.CHUNK / 2)]
) * 2 / (128 * self.CHUNK)
self.set_plotdata(name='spectrum', data_x=self.f, data_y=sp_data)
def animation(self):
timer = QtCore.QTimer()
timer.timeout.connect(self.update)
timer.start(20)
self.start()
if __name__ == '__main__':
audio_app = AudioStream()
audio_app.animation()
\ No newline at end of file
from tkinter import TclError
#Para disparar las gráficas en ventanas deparadas
#Se declaran las constantes para el objeto de pyaudio
CHUNK = 1024 * 2 #muetras por frame
FORMAT = pyaudio.paInt16 #formato de audio (bytes por muestra)
CHANNELS = 1 #Micrófono de un canal
RATE = 44100 #Frecuencia de muestreo
#Se crea el una figura de matplotlib con dos ejes y tamaño 15x7
fig, (ax1, ax2) = plt.subplots(2, figsize=(15, 7))
#Se crea una instancia de la clase pyaudio
p = pyaudio.PyAudio()
#Se crea un objeto stream para adquirir datos del micrófono
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK
)
#Se crea un arreglo de valores para graficar la señal
x = np.arange(0, 2 * CHUNK, 2)
#Arreglo para graficar el espectro
xf = np.linspace(0, RATE, CHUNK)
#Se crea un objeto línea para el eje de la gráfica de la señal
line, = ax1.plot(x, np.random.rand(CHUNK), '-', lw=2)
#objeto línea en escala logarítmica para la gráfica del espectro
line_fft, = ax2.semilogx(xf, np.random.rand(CHUNK), '-', lw=2)
#Formato ejes de la gráfica de la señal
ax1.set_title('Señal de entrada')
ax1.set_xlabel('muestras')
ax1.set_ylabel('amplitud')
ax1.set_ylim(0, 255)
ax1.set_xlim(0, 2 * CHUNK)
plt.setp(ax1, xticks=[0, CHUNK, 2 * CHUNK], yticks=[0, 128, 255])
#Formato ejes para la gráfica del espectro
ax2.set_xlim(20, RATE / 2)
print('Escuchando...')
frame_count = 0
start_time = time.time()
#loop
while True:
#Leer micrófono (data:binarios)
data = stream.read(CHUNK)
#Convertir data en enteros ...
data_int = struct.unpack(str(2 * CHUNK) + 'B', data)
# create np array and offset by 128
data_np = np.array(data_int, dtype='b')[::2] + 128
line.set_ydata(data_np)
# calcular la fft de los datos enteros
yf = fft(data_int)
line_fft.set_ydata(np.abs(yf[0:CHUNK]) / (128 * CHUNK))
# Actualizar la figura canvas
try:
fig.canvas.draw()
fig.canvas.flush_events()
frame_count += 1
except TclError:
# calcular el FPS promedio
frame_rate = frame_count / (time.time() - start_time)
print('Adquisición terminada')
print('FPS promedio = {:.0f} FPS'.format(frame_rate))
break
This diff is collapsed.
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