File size: 1,641 Bytes
12b9855
 
 
 
 
 
 
 
 
 
 
463ee22
 
 
 
 
12b9855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
import yt_dlp

app = FastAPI()

def get_m4a_url(video_url: str) -> str:
    """
    Extracts the best m4a audio stream URL from a YouTube video using yt_dlp with cookies.
    """
    ydl_opts = {
    'format': 'bestaudio[ext=m4a]/best',
    'quiet': True,
    'skip_download': True,
    'cookies_from_browser': 'chrome',  # automatically extract cookies from Chrome
    'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)...',
    }
    
    try:
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(video_url, download=False)
            
            # Try to find an m4a format URL
            for fmt in info.get('formats', []):
                if fmt.get('ext') == 'm4a' and fmt.get('url'):
                    return fmt.get('url')
            
            # Fallback to best audio URL if m4a is not found
            return info.get('url') if info.get('url') else None

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to extract audio: {str(e)}")

@app.get("/{video_id}")
def get_audio_url(video_id: str):
    """
    FastAPI endpoint to return the m4a audio stream URL in JSON format.
    """
    youtube_url = f"https://www.youtube.com/watch?v={video_id}"
    m4a_url = get_m4a_url(youtube_url)

    if not m4a_url:
        raise HTTPException(status_code=404, detail="m4a audio stream not found")

    return JSONResponse(content={"m4a_url": m4a_url})

if __name__ == "__main__":
    import uvicorn
    # Run on port 7860
    uvicorn.run(app, host="0.0.0.0", port=7860)