import os import time import subprocess from multiprocessing import Process import uvicorn from fastapi import FastAPI, Response app = FastAPI() # Archivo de audio y rutas de salida audio_file = "/app/theforgottenradio.mp3" hls_output = "/app/stream.m3u8" hls_segment_prefix = "/app/stream" # Comando FFmpeg para transmitir audio en HLS ffmpeg_command = [ 'ffmpeg', '-re', '-i', audio_file, '-c:a', 'aac', '-b:a', '128k', '-f', 'hls', '-hls_time', '10', '-hls_list_size', '0', '-hls_flags', 'delete_segments', '-hls_segment_filename', f'{hls_segment_prefix}%d.ts', # Nombre para los segmentos hls_output ] def stream_audio(): # Ejecuta el comando FFmpeg para iniciar la transmisión process = subprocess.Popen(ffmpeg_command) process.wait() def start_audio_streaming(): audio_process = Process(target=stream_audio) audio_process.start() @app.on_event("startup") async def startup_event(): # Espera activa para verificar que el archivo M3U8 esté generado while not os.path.exists(hls_output): print("Esperando a que se genere el archivo M3U8...") time.sleep(1) print("Archivo M3U8 generado. Servidor listo para recibir solicitudes.") @app.get("/") async def read_root(): return {"message": "Servidor de Radio M3U8 Activo"} @app.get("/stream.m3u8") def get_m3u8(): # Devuelve el archivo M3U8 generado with open(hls_output, "rb") as f: m3u8_content = f.read() return Response(content=m3u8_content, media_type="application/vnd.apple.mpegurl") @app.get("/stream{segment}.ts") def get_segment(segment: int): # Devuelve los segmentos TS generados segment_file = f"{hls_segment_prefix}{segment}.ts" if os.path.exists(segment_file): with open(segment_file, "rb") as f: segment_content = f.read() return Response(content=segment_content, media_type="video/mp2t") else: return Response(status_code=404, content="Segment not found") if __name__ == "__main__": start_audio_streaming() uvicorn.run(app, host="0.0.0.0", port=7860)