49 lines
1.6 KiB
Python
49 lines
1.6 KiB
Python
import asyncio
|
|
import aiohttp
|
|
from aiohttp import web
|
|
from aiohttp.web_ws import WebSocketResponse
|
|
from pydub import AudioSegment
|
|
import os
|
|
import io
|
|
import tempfile
|
|
|
|
|
|
async def handler(request):
|
|
counter = 0
|
|
# Valores de muestra
|
|
SAMPLE_WIDTH = 2
|
|
CHANNELS = 2
|
|
SAMPLE_RATE = 44100
|
|
|
|
# Duración de cada grabación
|
|
DURATION = 10 # 10 segundos
|
|
|
|
# Tamaño total de la grabación (en bytes)
|
|
TOTAL_SIZE = SAMPLE_WIDTH * CHANNELS * SAMPLE_RATE * DURATION
|
|
|
|
ws = WebSocketResponse()
|
|
await ws.prepare(request)
|
|
async for msg in ws:
|
|
if msg.type == aiohttp.WSMsgType.BINARY:
|
|
audio_data = msg.data
|
|
counter += len(audio_data) # aumenta el contador
|
|
|
|
if counter >= TOTAL_SIZE:
|
|
# escribe los datos de audio en un archivo temporal
|
|
with tempfile.NamedTemporaryFile(mode='wb+',dir='./', delete=False) as f:
|
|
f.write(audio_data)
|
|
f.flush()
|
|
# convertir los datos de audio a un objeto de tipo AudioSegment
|
|
audio_segment = AudioSegment.from_raw(f.name, sample_width=SAMPLE_WIDTH, channels=CHANNELS, frame_rate=SAMPLE_RATE)
|
|
# convertir los datos de audio a un objeto de tipo AudioSegment
|
|
|
|
# guarda el objeto en un archivo .wav
|
|
audio_segment.export("output.wav", format="wav")
|
|
|
|
counter = 0 # reinicia el contador
|
|
|
|
return ws
|
|
|
|
app = web.Application()
|
|
app.add_routes([web.get('/', handler)])
|
|
web.run_app(app, host='localhost', port=8000) |