Chuyển đến nội dung
VI
Lấy khóa API

YouTube Download / Python

Tải về YouTube âm thanh cho âm thanh của bạn S3 xô

Gửi một file ghi âm, theo dõi công việc nền và lấy vị trí tập tin MP3 đã gửi.

FlashData · Xuất bản

Name

Chuẩn bị xô đi

Anh cần Python 3, a FlashData API Chìa khóa với tín dụng sẵn có, một Amazon S3 Giấy ủy quyền và giấy tờ lưu trữ có thể viết cho cái xô đó. Giữ những giấy tờ đó trong máy chủ của anh.

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'

Hãy dùng khu vực xô thực sự của bạn. MEDIA_BUCKET là tên xô, không có một s3:// Tiền tố hoặc đường dẫn thư mục. Xem các Thiết lập kho lưu Vì S3- Điểm đến tương xứng.

Gửi và theo dõi việc tải về

Lưu văn lệnh dạng delivery.py. Nó gửi một đoạn ghi âm đến POST /v1/queries, chọn kết xuất MP3 và cung cấp S3 Địa điểm.

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

Văn lệnh in ra công việc ID Trước khi bỏ phiếu. Lưu cái đó đi. ID trong ứng dụng của bạn, vì vậy một chương trình chạy lại hoặc thời hạn không mất liên kết để làm việc đã gửi.

Đọc biên lai công việc

Việc tải về đã gửi hóa đơn, không phải tập tin truyền thông. Hóa đơn ghi âm này chứa công việc ID và các liên kết dùng để theo dõi sự tiến bộ và đọc kết quả cuối cùng.

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"
    }
  ]
}

Sử dụng cùng một phím API để đọc liên kết trạng thái. Nếu hạn bỏ phiếu hết hạn, hãy giữ ID và kiểm tra sau. Không tự động tạo một công việc thay thế.

Dùng tập tin đã gửi

Một khi tập tin đã được tải lên, công việc sẽ trở thành completed. Kết quả chuyển hướng điểm kết thúc sang cất giữ JSON; văn lệnh theo đó chuyển hướng mà không chuyển tiếp của bạn API Chìa khóa kho.

Đọc file_url, file_size và các trường đầu ra từ kết quả. Để có một xô riêng, hãy dùng giấy ủy nhiệm lưu trữ để đọc tập tin hoặc tạo một liên kết đã ký cho người dùng cuối cùng. Tập tin URL bản thân không làm cho đối tượng công khai.

Giữ lại công việc JSON Kết quả bên trong nó 24- thời gian lưu trữ hàng giờ. Các vật thể truyền thông vẫn còn nằm trong tầm kiểm soát của những chiếc xe đạp kéo của bạn. Việc tải về được dựa trên âm lượng của dữ liệu đã tải về.