mirror of
https://github.com/wahyd4/you-music.git
synced 2026-08-09 13:16:30 +10:00
46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
from fastapi import APIRouter, HTTPException
|
|
from fastapi.responses import RedirectResponse
|
|
import yt_dlp
|
|
from app.core.config import settings
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/stream")
|
|
async def stream_music(url: str):
|
|
"""Get direct streaming URL for YouTube/Bilibili video"""
|
|
try:
|
|
ydl_opts = {
|
|
'format': 'bestaudio/best',
|
|
'quiet': True,
|
|
'no_warnings': True,
|
|
'extract_flat': False,
|
|
}
|
|
|
|
if settings.PROXY:
|
|
ydl_opts['proxy'] = settings.PROXY
|
|
|
|
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
info = ydl.extract_info(url, download=False)
|
|
|
|
# Get the direct audio URL
|
|
if 'url' in info:
|
|
direct_url = info['url']
|
|
elif 'formats' in info:
|
|
# Find best audio format
|
|
audio_formats = [f for f in info['formats'] if f.get('acodec') != 'none']
|
|
if audio_formats:
|
|
# Sort by quality and get best
|
|
audio_formats.sort(key=lambda x: x.get('abr', 0) or 0, reverse=True)
|
|
direct_url = audio_formats[0]['url']
|
|
else:
|
|
raise HTTPException(status_code=404, detail="No audio stream found")
|
|
else:
|
|
raise HTTPException(status_code=404, detail="No stream URL found")
|
|
|
|
# Redirect to the direct URL
|
|
return RedirectResponse(url=direct_url)
|
|
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=f"Stream extraction failed: {str(e)}")
|