ข้ามไปยังเนื้อหา
TH
รับคีย์ API

YouTube Download / Python

ดาวน์โหลด YouTube เสียงถึงคุณ S3 ถัง

ส่งการดาวน์โหลดเสียง, ติดตามงานพิมพ์เบื้องหลัง และดึงข้อมูลตําแหน่งของแฟ้ม MP3 ที่ส่งมาแล้ว

FlashData · จัดพิมพ์

คลื่นเสียงที่จะส่งไปยังคลังวัตถุ

เตรียมถังของคุณ

คุณต้องการ Python 3, FlashData API กุญแจพร้อมเครดิตที่มี, Amazon S3 ถังและบันทึกเอกสารที่สามารถเขียนไปยังถังที่ เก็บเอกสารพวกนั้นไว้ที่เซิร์ฟเวอร์ของคุณ

bash
# Replace YOUR_API_KEY near the top of the code below.
export YOUTUBE_VIDEO_ID='FUfGcZ092b0'
export MEDIA_BUCKET='your-media-bucket'
export AWS_REGION='us-east-1'
export MEDIA_ACCESS_KEY='your-storage-access-key'
export MEDIA_SECRET_KEY='your-storage-secret-key'

ใช้พื้นที่ถังจริงๆของคุณ MEDIA_BUCKET คือชื่อถังที่ไม่มี s3:// นําหน้าหรือพาธไดเรกทอรี ดู ตั้งค่าการจัดเก็บ สําหรับ S3 จุดหมายปลายทางที่เข้ากันได้

ส่งและติดตามการดาวน์โหลด

บันทึกสคริปต์เป็น delivery.py. มันส่งการดาวน์โหลดเสียงไปยัง POST /v1/queries, เลือกผลลัพธ์ MP3 และให้ S3 จุดหมาย

python
import json
import gzip
import os
import urllib.error
import urllib.request

API_URL = "https://data.flashdata.dev"
API_KEY = "YOUR_API_KEY"


def api_request(path, payload=None, response_headers=None, base_url=API_URL):
    target = path if path.startswith(("https://", "http://")) else base_url + path
    request = urllib.request.Request(
        target,
        data=json.dumps(payload).encode() if payload is not None else None,
        headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
        method="POST" if payload is not None else "GET",
    )
    with urllib.request.urlopen(request, timeout=60) as response:
        if response_headers is not None:
            response_headers.update(response.headers)
        return json.load(response)


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, request, file_pointer, code, message, headers, new_url):
        return None


def result_request(url):
    request = urllib.request.Request(url, headers={"X-API-Key": API_KEY}, method="GET")
    try:
        with urllib.request.build_opener(NoRedirect).open(request, timeout=60):
            raise RuntimeError("Results endpoint did not redirect to storage")
    except urllib.error.HTTPError as response:
        if response.code != 302 or not response.headers.get("Location"):
            raise
        storage_url = response.headers["Location"]
        response.close()
    storage_request = urllib.request.Request(storage_url, headers={"Accept-Encoding": "gzip"})
    with urllib.request.urlopen(storage_request, timeout=60) as response:
        body = response.read()
        if response.headers.get("Content-Encoding") == "gzip":
            body = gzip.decompress(body)
        return json.loads(body)["results"]

import random
import time


def wait_for_job(submission, timeout_seconds=300):
    job_id = submission["id"]
    status_url = next(link["href"] for link in submission["links"] if link["rel"] == "self")
    deadline = time.monotonic() + timeout_seconds
    delay = 1.0
    while time.monotonic() < deadline:
        headers = {}
        payload = api_request(status_url, response_headers=headers)
        job = payload.get("job", payload)
        if job["status"] == "completed":
            results_url = next(link["href"] for link in job["links"] if link["rel"] == "results")
            return result_request(results_url)
        if job["status"] == "failed":
            raise RuntimeError(f"{job_id}: {job.get('error') or 'Job failed'}")
        hint = headers.get("Retry-After", headers.get("retry-after", "1"))
        delay = max(min(5.0, delay * 1.5), float(hint))
        time.sleep(min(delay * random.uniform(1.0, 1.2), max(0, deadline - time.monotonic())))
    raise TimeoutError(f"Keep this job ID and check again later: {job_id}")

storage = {
    "storage_type": "s3",
    "storage_url": os.environ["MEDIA_BUCKET"],
    "object_prefix": "YYYYMMDD",
    "region": os.environ["AWS_REGION"],
    "access_key": os.environ["MEDIA_ACCESS_KEY"],
    "secret_key": os.environ["MEDIA_SECRET_KEY"],
}

job = api_request("/v1/queries", {
    "source": "youtube_download",
    "video_id": os.environ["YOUTUBE_VIDEO_ID"],
    "params": {
        "download_type": "audio",
        "output_format": "mp3",
        "storage": storage,
    },
})
print("Save this job ID before polling:", job["id"], flush=True)
files = wait_for_job(job)
print(json.dumps(files, indent=2))
bash
python3 delivery.py

สคริปต์พิมพ์งาน ID ก่อนทําโพล บันทึกที่ ID ในโปรแกรมของคุณ เพื่อให้มีการเริ่มการทํางานหรือหมดเวลาอีกครั้ง จะไม่มีการสูญเสียการเชื่อมโยงที่จะทํางานได้

อ่านใบเสร็จงาน

การส่งข้อมูลลงแผ่น จะคืนค่ากลับมาเป็นใบเสร็จ ไม่ใช่แฟ้มสื่อ ใบเสร็จนี้บรรจุงาน ID และลิงก์ที่ใช้ติดตามความคืบหน้าและอ่านผลที่ออกมา

json
{
  "id": "job_d265c693-950e-40bf-a13e-a432044d99ba",
  "source": "youtube_download",
  "status": "pending",
  "usage": {
    "credits": 0
  },
  "created_at": "2026-09-16T07:51:13.139Z",
  "links": [
    {
      "rel": "self",
      "href": "https://api.flashdata.dev/v2/jobs/job_d265c693-950e-40bf-a13e-a432044d99ba",
      "method": "GET"
    },
    {
      "rel": "results",
      "href": "https://api.flashdata.dev/v2/jobs/job_d265c693-950e-40bf-a13e-a432044d99ba/results",
      "method": "GET"
    }
  ]
}

ใช้แบบเดียวกัน API กุญแจที่จะอ่านที่อยู่เชื่อมโยง ถ้าเส้นตายการสํารวจหมดอายุ ให้เก็บ ID และตรวจสอบในภายหลัง อย่าสร้างงานใหม่ให้โดยอัตโนมัติ

ใช้แฟ้มส่ง

เมื่อแฟ้มถูกอัปโหลด งานก็กลายเป็น completed. ส่วนเปลี่ยนปลายทางที่จะจัดเก็บ JSONสคริปต์จะติดตามการเปลี่ยนเส้นทางโดยไม่ส่งต่อ API กุญแจสําคัญในการเก็บ

อ่าน file_url, file_size และสนามส่งผลจากผลลัพธ์ สําหรับถังส่วนตัว ให้ใช้ข้อมูลส่วนตัวของคุณในการอ่านแฟ้ม หรือสร้างลิงก์ที่ลงนามสําหรับผู้ใช้ปลายทางของคุณ แฟ้ม URL เองไม่ได้ทําให้วัตถุเป็นสาธารณะ

ช่วย เหลือ งาน JSON ส่งผลให้ภายใน 24- ระยะเวลาพักหลัง เป้า หมาย ของ สื่อ ยัง คง อยู่ ภาย ใต้ สภาพ แวด ล้อม ของ รถ จักรยานยนต์ ของ คุณ เอง. การใช้การดาวน์โหลดเป็นพื้นฐาน จากปริมาณข้อมูลที่ดาวน์โหลดมา