|
from fastapi import FastAPI, HTTPException, Query |
|
from fastapi.responses import RedirectResponse |
|
import subprocess |
|
|
|
app = FastAPI( |
|
title="YouTube Audio Streamer", |
|
description="Stream best audio of a YouTube video using yt-dlp.", |
|
version="1.0.1", |
|
docs_url="/docs", |
|
redoc_url="/redoc" |
|
) |
|
|
|
@app.get("/", tags=["Health"]) |
|
async def root(): |
|
return {"status": "FastAPI working", "message": "YT-DLP backend ready"} |
|
|
|
@app.get("/stream", tags=["Stream"]) |
|
async def stream_audio(url: str = Query(..., description="Full YouTube video URL")): |
|
if "youtube.com/watch?v=" not in url and "youtu.be/" not in url: |
|
raise HTTPException(status_code=400, detail="Invalid YouTube URL.") |
|
|
|
try: |
|
result = subprocess.run( |
|
["yt-dlp", "-f", "bestaudio", "--get-url", url], |
|
capture_output=True, text=True |
|
) |
|
audio_url = result.stdout.strip() |
|
if not audio_url: |
|
raise HTTPException(status_code=404, detail="No audio URL found.") |
|
return RedirectResponse(audio_url) |
|
except Exception as e: |
|
raise HTTPException(status_code=500, detail=f"Error: {str(e)}") |