# YouTube Audio Segment Downloader (`entertained_rattlesnake/youtube-audio-segment-downloader`) Actor

Download YouTube audio tracks or selected audio segments as MP3, M4A, or WAV.

- **URL**: https://apify.com/entertained\_rattlesnake/youtube-audio-segment-downloader.md
- **Developed by:** [Entertained Rattlesnake](https://apify.com/entertained_rattlesnake) (community)
- **Categories:** AI, Developer tools, Videos
- **Stats:** 3 total users, 1 monthly users, 100.0% runs succeeded, NaN bookmarks
- **User rating**: No ratings yet

## Pricing

from $40.00 / 1,000 audio minute processeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## YouTube Audio Segment Downloader

Download YouTube audio (or a specific segment), transcribe it, and push the transcript to the Apify Dataset.

The Actor supports MP3, M4A, and WAV output formats. When `startTime` and/or `endTime` are provided, the Actor downloads only the requested section using `yt-dlp --download-sections` instead of downloading the full audio first. Audio files are stored in the Key-Value Store; the Dataset receives one item per successful video with the same minimal schema as `entertained_rattlesnake/youtube-subtitle-scraper-ai`.

Use this Actor only for videos you own, videos licensed for reuse, or videos where you have permission to download and process the audio.

### Features

- Download YouTube audio
- Download only a selected audio segment (`90`, `1:30`, `00:01:30`)
- Supports MP3, M4A, and WAV
- Audio files saved to Key-Value Store
- Built-in transcription via configurable HTTP endpoint (default: Whisper)
- Optional `[HH:MM:SS.mmm]` timestamps in the transcript
- Dataset schema compatible with `entertained_rattlesnake/youtube-subtitle-scraper-ai`
- Built-in proxy fallback (residential → datacenter → auto → none)

### Input

```json
{
  "videos": [
    "https://www.youtube.com/watch?v=qb15hppy9rI"
  ],
  "format": "mp3",
  "audioQuality": "192k",
  "startTime": "00:01:30",
  "endTime": "00:03:00",
  "fileNamePrefix": "youtube-audio",
  "maxFileSizeMb": 500,
  "transcribe": true,
  "transcribeTimeoutSeconds": 600,
  "timestamps": false
}```

- `videos` — list of YouTube URLs or 11-character video IDs.
- `timestamps` — if `true`, each line of the returned `text` is prefixed with `[HH:MM:SS.mmm]`.
- `transcribe`, `transcribeTimeoutSeconds` — control transcription behaviour. The transcription endpoint URL is hardcoded inside the Actor and is not user-configurable.
- `startTime` / `endTime` — optional segment bounds.

### Output

Each successfully transcribed video produces one Dataset item with the schema below. Failed runs are written to the Key-Value Store as `FAILED_<videoId>.json` and are NOT pushed to the Dataset (this matters for pay-per-result monetization).

| Field | Type | Description |
| --- | --- | --- |
| `videoUrl` | `string` (uri) | Canonical URL of the YouTube video. |
| `videoId` | `string` | 11-character YouTube video identifier. |
| `videoTitle` | `string \| null` | Video title as reported by YouTube. |
| `channelName` | `string \| null` | Display name of the channel that published the video. |
| `views` | `string \| null` | View count at the time of extraction. |
| `text` | `string` | Full transcript. Includes `[HH:MM:SS.mmm]` prefixes when `timestamps` is `true`. |

Example item:

```json
[
  {
    "videoUrl": "https://www.youtube.com/watch?v=qb15hppy9rI",
    "videoId": "qb15hppy9rI",
    "videoTitle": "З нами сьогодні Ігор Закотинський...",
    "channelName": "Example channel",
    "views": "1933",
    "text": "З нами сьогодні Ігор Закотинський, той самий син маминої подриги..."
  }
]
````

#### Side outputs (Key-Value Store)

- `AUDIO_<videoId>_<timestamp>.<ext>` — converted audio file.
- `TRANSCRIPT_<videoId>_<timestamp>.json` — full transcription response (segments, language, duration, etc.).
- `FAILED_<videoId>.json` — failure details for items that did not produce a Dataset record.
- `SUMMARY` — run summary.

#### Proxy

The Actor uses Apify Proxy automatically — there is no input field for it. Each `yt-dlp` call iterates through a built-in fallback chain until one succeeds:

1. `RESIDENTIAL` group (preferred — YouTube blocks datacenter IPs aggressively)
2. Datacenter group (`BUYPROXIES94952`)
3. Default Apify Proxy (auto)
4. No proxy (last resort)

A separate proxy session is used per video so retries for the same video stick to the same IP.

#### Transcription

When `transcribe` is `true`, the saved audio file is sent to the built-in transcription endpoint as `multipart/form-data` with a single `file` field. The endpoint is expected to return JSON with at least `status`, `language`, `duration_seconds`, `text`, and `segments`. If transcription fails, the video is treated as failed (no Dataset record).

### Pricing (Pay per event)

The Actor is monetized via Apify's **Pay-per-event** model. Two events are emitted by the Actor and must be configured in the Apify Console (Actor → Monetization → Pay per event):

| Event ID | When it fires | Recommended price (USD) | Covers |
| --- | --- | --- | --- |
| `video-started` | Once per video, immediately after YouTube metadata is fetched successfully. | **$0.05** | Fixed overhead: metadata fetch, proxy retries, KV-store writes, run startup. |
| `audio-minute-processed` | Once per successful Dataset item, with `count = ceil(durationSeconds / 60)`. Duration is taken from the transcription response when available, otherwise from the requested segment / video metadata. | **$0.03** per minute | Residential proxy data transfer (~$8/GB), CPU/RAM compute, external data transfer, and transcription server time. |

Failed videos are **not** charged for `audio-minute-processed` (only `video-started` is charged once the metadata fetch succeeds).

#### Example prices for the end user

| Audio length | Charge breakdown | Total |
| --- | --- | --- |
| 1 minute | `$0.05` + `1 × $0.03` | **$0.08** |
| 5 minutes | `$0.05` + `5 × $0.03` | **$0.20** |
| 15 minutes | `$0.05` + `15 × $0.03` | **$0.50** |
| 30 minutes | `$0.05` + `30 × $0.03` | **$0.95** |
| 60 minutes | `$0.05` + `60 × $0.03` | **$1.85** |

#### How to configure in Apify Console

1. Open the Actor → **Monetization** → choose **Pay per event**.
2. Add the two events above with the exact IDs `video-started` and `audio-minute-processed` and the prices from the table.
3. Optionally set a global `maxTotalChargeUsd` per run as a safety cap.

The SDK calls (`Actor.charge({ eventName, count })`) live in `src/charging.js` and are invoked from `src/processVideo.js`. If an event is not configured in the Console the SDK silently skips the charge — the Actor will still run, it just will not bill the user.

# Actor input Schema

## `videos` (type: `array`):

List of YouTube video URLs or video IDs.

## `format` (type: `string`):

Audio format for the output file.

## `audioQuality` (type: `string`):

Audio bitrate for MP3/M4A conversion. Use 64 kbps for transcription-only workflows to minimize proxy traffic and processing cost.

## `startTime` (type: `string`):

Optional start time. Examples: 90, 1:30, 00:01:30.

## `endTime` (type: `string`):

Optional end time. Examples: 180, 3:00, 00:03:00.

## `fileNamePrefix` (type: `string`):

Prefix for output files.

## `maxFileSizeMb` (type: `integer`):

Maximum output file size in MB. If exceeded, the result will not be saved.

## `transcribe` (type: `boolean`):

If enabled, the saved audio file is sent to the transcription endpoint and the result is saved to the Key-Value Store.

## `transcribeTimeoutSeconds` (type: `integer`):

Maximum time to wait for the transcription endpoint response.

## `timestamps` (type: `boolean`):

If true, prepends each line of the returned text with a \[HH:MM:SS.mmm] timestamp.

## Actor input object example

```json
{
  "videos": [
    "https://www.youtube.com/watch?v=qb15hppy9rI"
  ],
  "format": "mp3",
  "audioQuality": "192k",
  "fileNamePrefix": "youtube-audio",
  "maxFileSizeMb": 500,
  "transcribe": true,
  "transcribeTimeoutSeconds": 600,
  "timestamps": false
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "videos": [
        "https://www.youtube.com/watch?v=qb15hppy9rI"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("entertained_rattlesnake/youtube-audio-segment-downloader").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "videos": ["https://www.youtube.com/watch?v=qb15hppy9rI"] }

# Run the Actor and wait for it to finish
run = client.actor("entertained_rattlesnake/youtube-audio-segment-downloader").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "videos": [
    "https://www.youtube.com/watch?v=qb15hppy9rI"
  ]
}' |
apify call entertained_rattlesnake/youtube-audio-segment-downloader --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=entertained_rattlesnake/youtube-audio-segment-downloader",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "YouTube Audio Segment Downloader",
        "description": "Download YouTube audio tracks or selected audio segments as MP3, M4A, or WAV.",
        "version": "1.0",
        "x-build-id": "5nK8KTlZO4Ni4G99X"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/entertained_rattlesnake~youtube-audio-segment-downloader/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-entertained_rattlesnake-youtube-audio-segment-downloader",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/entertained_rattlesnake~youtube-audio-segment-downloader/runs": {
            "post": {
                "operationId": "runs-sync-entertained_rattlesnake-youtube-audio-segment-downloader",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/entertained_rattlesnake~youtube-audio-segment-downloader/run-sync": {
            "post": {
                "operationId": "run-sync-entertained_rattlesnake-youtube-audio-segment-downloader",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "videos"
                ],
                "properties": {
                    "videos": {
                        "title": "YouTube videos",
                        "type": "array",
                        "description": "List of YouTube video URLs or video IDs.",
                        "items": {
                            "type": "string"
                        }
                    },
                    "format": {
                        "title": "Output audio format",
                        "enum": [
                            "mp3",
                            "m4a",
                            "wav"
                        ],
                        "type": "string",
                        "description": "Audio format for the output file.",
                        "default": "mp3"
                    },
                    "audioQuality": {
                        "title": "Audio quality",
                        "enum": [
                            "64k",
                            "128k",
                            "192k",
                            "256k",
                            "320k"
                        ],
                        "type": "string",
                        "description": "Audio bitrate for MP3/M4A conversion. Use 64 kbps for transcription-only workflows to minimize proxy traffic and processing cost.",
                        "default": "192k"
                    },
                    "startTime": {
                        "title": "Start time",
                        "type": "string",
                        "description": "Optional start time. Examples: 90, 1:30, 00:01:30."
                    },
                    "endTime": {
                        "title": "End time",
                        "type": "string",
                        "description": "Optional end time. Examples: 180, 3:00, 00:03:00."
                    },
                    "fileNamePrefix": {
                        "title": "File name prefix",
                        "type": "string",
                        "description": "Prefix for output files.",
                        "default": "youtube-audio"
                    },
                    "maxFileSizeMb": {
                        "title": "Max output file size MB",
                        "minimum": 1,
                        "maximum": 2000,
                        "type": "integer",
                        "description": "Maximum output file size in MB. If exceeded, the result will not be saved.",
                        "default": 500
                    },
                    "transcribe": {
                        "title": "Transcribe audio",
                        "type": "boolean",
                        "description": "If enabled, the saved audio file is sent to the transcription endpoint and the result is saved to the Key-Value Store.",
                        "default": true
                    },
                    "transcribeTimeoutSeconds": {
                        "title": "Transcription timeout (seconds)",
                        "minimum": 10,
                        "maximum": 3600,
                        "type": "integer",
                        "description": "Maximum time to wait for the transcription endpoint response.",
                        "default": 600
                    },
                    "timestamps": {
                        "title": "Include timestamps",
                        "type": "boolean",
                        "description": "If true, prepends each line of the returned text with a [HH:MM:SS.mmm] timestamp.",
                        "default": false
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
