Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Cloudflare Workers AI で Whisper-large-v3-turbo を使う

最終更新 Markdown で表示Agent セットアップ

このチュートリアルでは、次のことを学びます。

  • 大きな音声ファイルの文字起こし: Cloudflare Workers AI の Whisper-large-v3-turbo モデルで、自動音声認識(ASR)または翻訳を実行します。
  • 大きなファイルの扱い: 大きな音声ファイルを小さなチャンクに分割して処理します。メモリと実行時間の制限を避けるのに役立ちます。
  • Cloudflare Workers でのデプロイ: サーバーレス環境で、スケールしやすく低遅延の文字起こしパイプラインを作ります。

1: 新しい Cloudflare Worker プロジェクトを作る

  1. Cloudflare アカウント に登録します。
  2. Node.js をインストールします。

Node.js のバージョンマネージャー

権限の問題を避け、Node.js のバージョンを切り替えられるよう、Voltanvm などの Node バージョンマネージャーを使います。このガイドの後半で説明する Wrangler には、Node バージョン 16.17.0 以降が必要です。

create-cloudflare CLI(C3)で、新しい Worker プロジェクトを作ります。C3 は、Cloudflare 向けの新しいアプリケーションのセットアップとデプロイを支援するコマンドラインツールです。

次を実行して、whisper-tutorial という名前の新しいプロジェクトを作ります。

npm create cloudflare@latest -- whisper-tutorial

npm create cloudflare@latest を実行すると、create-cloudflare パッケージ のインストールを求められ、セットアップが進みます。C3 は、Cloudflare Developer Platform の CLI である Wrangler もインストールします。

セットアップでは、次のオプションを選びます。

  • What would you like to start with? では、Hello World example を選びます。
  • Which template would you like to use? では、Worker only を選びます。
  • Which language do you want to use? では、TypeScript を選びます。
  • Do you want to use git for version control? では、Yes を選びます。
  • Do you want to deploy your application? では、No を選びます(デプロイ前にいくつか変更します)。

これで新しい whisper-tutorial ディレクトリができます。このディレクトリには次が含まれます。

アプリケーションのディレクトリに移動します。

cd whisper-tutorial

2. Worker を Workers AI に接続する

Worker を Workers AI に接続するには、AI バインディングを作ります。バインディング により、Workers は Cloudflare Developer Platform 上の Workers AI などのリソースと連携できます。

Workers AI を Worker にバインドするには、Wrangler 設定ファイルの末尾に次を追加します。

{
	"ai": {
		"binding": "AI"
	}
}
[ai]
binding = "AI"

バインディングは、Worker コードの env.AI利用できます

3. Wrangler を設定する

wrangler ファイルで、次の設定を追加または更新し、Node.js API とポリフィルを有効にします(互換日は 2024-09-23 以降)。

{
	"compatibility_flags": [
		"nodejs_compat"
	],
	// Set this to today's date
	"compatibility_date": "2026-09-20"
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-09-20"

4. チャンク分割で大きな音声ファイルを扱う

src/index.ts の内容を、次の統合コードに置き換えます。このサンプルは次を示します。

(1) クエリパラメーターから音声ファイルの URL を取り出します。

(2) リダイレクトを明示的にたどりながら、音声ファイルを取得します。

(3) 音声ファイルを小さなチャンク(例: 1 MB)に分割します。

(4) Cloudflare AI バインディング経由で、Whisper-large-v3-turbo モデルを使って各チャンクを文字起こしします。

(5) 集約した文字起こし結果をプレーンテキストで返します。

import { Buffer } from "node:buffer";
import type { Ai } from "workers-ai";

export interface Env {
	AI: Ai;
	// If needed, add your KV namespace for storing transcripts.
	// MY_KV_NAMESPACE: KVNamespace;
}

/**
 * Fetches the audio file from the provided URL and splits it into chunks.
 * This function explicitly follows redirects.
 *
 * @param audioUrl - The URL of the audio file.
 * @returns An array of ArrayBuffers, each representing a chunk of the audio.
 */
async function getAudioChunks(audioUrl: string): Promise<ArrayBuffer[]> {
	const response = await fetch(audioUrl, { redirect: "follow" });
	if (!response.ok) {
		throw new Error(`Failed to fetch audio: ${response.status}`);
	}
	const arrayBuffer = await response.arrayBuffer();

	// Example: Split the audio into 1MB chunks.
	const chunkSize = 1024 * 1024; // 1MB
	const chunks: ArrayBuffer[] = [];
	for (let i = 0; i < arrayBuffer.byteLength; i += chunkSize) {
		const chunk = arrayBuffer.slice(i, i + chunkSize);
		chunks.push(chunk);
	}
	return chunks;
}

/**
 * Transcribes a single audio chunk using the Whisper‑large‑v3‑turbo model.
 * The function converts the audio chunk to a Base64-encoded string and
 * sends it to the model via the AI binding.
 *
 * @param chunkBuffer - The audio chunk as an ArrayBuffer.
 * @param env - The Cloudflare Worker environment, including the AI binding.
 * @returns The transcription text from the model.
 */
async function transcribeChunk(
	chunkBuffer: ArrayBuffer,
	env: Env,
): Promise<string> {
	const base64 = Buffer.from(chunkBuffer, "binary").toString("base64");
	const res = await env.AI.run("@cf/openai/whisper-large-v3-turbo", {
		audio: base64,
		// Optional parameters (uncomment and set if needed):
		// task: "transcribe",   // or "translate"
		// language: "en",
		// vad_filter: "false",
		// initial_prompt: "Provide context if needed.",
		// prefix: "Transcription:",
	});
	return res.text; // Assumes the transcription result includes a "text" property.
}

/**
 * The main fetch handler. It extracts the 'url' query parameter, fetches the audio,
 * processes it in chunks, and returns the full transcription.
 */
export default {
	async fetch(
		request: Request,
		env: Env,
		ctx: ExecutionContext,
	): Promise<Response> {
		// Extract the audio URL from the query parameters.
		const { searchParams } = new URL(request.url);
		const audioUrl = searchParams.get("url");

		if (!audioUrl) {
			return new Response("Missing 'url' query parameter", { status: 400 });
		}

		// Get the audio chunks.
		const audioChunks: ArrayBuffer[] = await getAudioChunks(audioUrl);
		let fullTranscript = "";

		// Process each chunk and build the full transcript.
		for (const chunk of audioChunks) {
			try {
				const transcript = await transcribeChunk(chunk, env);
				fullTranscript += transcript + "\n";
			} catch (error) {
				fullTranscript += "[Error transcribing chunk]\n";
			}
		}

		return new Response(fullTranscript, {
			headers: { "Content-Type": "text/plain" },
		});
	},
} satisfies ExportedHandler<Env>;

5. Worker をデプロイする

  1. Worker をローカルで実行します。

    wrangler の開発モードで、Worker をローカルテストします。

npx wrangler dev

ブラウザーで http://localhost:8787 を開くか、curl を使います。

curl "http://localhost:8787?url=https://raw.githubusercontent.com/your-username/your-repo/main/your-audio-file.mp3"

URL クエリパラメーターを、音声ファイルへの直接リンクに置き換えます。(GitHub 上のファイルでは、raw ファイルの URL を使ってください。)

  1. Worker をデプロイします。

    テストが終わったら、次で Worker をデプロイします。

npx wrangler deploy
  1. デプロイした Worker をテストします。

    デプロイ後、音声 URL をクエリパラメーターとして渡して Worker をテストします。

curl "https://<your-worker-subdomain>.workers.dev?url=https://raw.githubusercontent.com/your-username/your-repo/main/your-audio-file.mp3"

<your-worker-subdomain>your-usernameyour-repoyour-audio-file.mp3 は、実際の値に置き換えてください。

成功すると、Worker は音声ファイルの文字起こしを返します。

This is the transcript of the audio...

役に立ちましたか?