> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# 音楽クイックスタート

このガイドでは、Music APIを使って音楽を生成する方法を紹介します。

> **Tip**
>
> [ElevenLabs music skill](https://github.com/elevenlabs/skills/tree/main/music)を使うと、AIコーディングアシスタントから音楽トラックを生成できます。
>
> ```bash
> npx skills add elevenlabs/skills --skill music
> ```

> **Info**
>
> Music APIは有料ユーザーのみご利用いただけます。

## Music APIの使い方

#### APIキーを作成

[ダッシュボードでAPIキーを作成](https://elevenlabs.io/app/settings/api-keys)し、安全に[APIへアクセス](/docs/ja/api-reference/authentication)するために使用します。

キーは管理されたシークレットとして保存し、好みに応じて`.env`ファイルによる環境変数として、またはアプリの設定で直接SDKに渡してください。

**`.env`**

```js title=".env"
ELEVENLABS_API_KEY=<your_api_key_here>
```

#### SDKをインストール

#### SDK

`dotenv`ライブラリも使用して、環境変数からAPIキーを読み込みます。

```python
pip install elevenlabs
pip install python-dotenv
```

```typescript
npm install @elevenlabs/elevenlabs-js
npm install dotenv
```

#### CLI

ElevenLabs CLIをインストールします。Homebrew（macOS）とScoop（Windows）を推奨します。

**`Homebrew (macOS)`**

```bash title="Homebrew (macOS)"
brew install elevenlabs/tap/elevenlabs
```

**`Scoop (Windows)`**

```powershell title="Scoop (Windows)"
scoop bucket add elevenlabs https://github.com/elevenlabs/scoop-bucket
scoop install elevenlabs
```

**`npm`**

```bash title="npm"
npm install -g @elevenlabs/cli
```

**`curl`**

```bash title="curl"
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/elevenlabs/cli/releases/latest/download/elevenlabs-cli-installer.sh | sh
```

> **Tip**
>
> AIコーディングアシスタントを使っていますか？プロジェクトで`elevenlabs generate-skills`を実行すると、各コマンドグループ用の
> `SKILL.md`が`skills/`に作成されます。これにより、ドキュメントを貼り付けなくても、アシスタントがCLIのすべての機能を把握できます。
> 別の場所に配置するには`--output-dir`を使ってください。CLIに組み込まれたAPI定義を読み取るため、APIキーは不要で、オフラインでも動作します。また、
> インストールしているCLIのバージョンに常に対応します。

次に認証します。ブラウザが開き、CLIを承認できます。

```bash
elevenlabs auth login
```

#### APIリクエストを実行

#### SDK

使用する言語に応じて、`example.py`または`example.mts`という名前の新しいファイルを作成し、次のコードを追加します。

```python
# example.py
from elevenlabs.client import ElevenLabs
from elevenlabs.play import play
import os
from dotenv import load_dotenv
load_dotenv()

elevenlabs = ElevenLabs(
    api_key=os.getenv("ELEVENLABS_API_KEY"),
)

track = elevenlabs.music.compose(
    prompt="Create an intense, fast-paced electronic track for a high-adrenaline video game scene. Use driving synth arpeggios, punchy drums, distorted bass, glitch effects, and aggressive rhythmic textures. The tempo should be fast, 130–150 bpm, with rising tension, quick transitions, and dynamic energy bursts.",
    music_length_ms=10000,
    model_id="music_v2_5",
)

# Save the track to a file
with open("path/to/music.mp3", "wb") as f:
    for chunk in track:
        f.write(chunk)
```

```typescript
// example.mts
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
import { Readable } from "stream";
import { createWriteStream } from "fs";
import { pipeline } from "stream/promises";
import "dotenv/config";

const elevenlabs = new ElevenLabsClient();

const track = await elevenlabs.music.compose({
  prompt: "Create an intense, fast-paced electronic track for a high-adrenaline video game scene. Use driving synth arpeggios, punchy drums, distorted bass, glitch effects, and aggressive rhythmic textures. The tempo should be fast, 130–150 bpm, with rising tension, quick transitions, and dynamic energy bursts.",
  musicLengthMs: 10000,
  modelId: "music_v2_5",
});

// Save the track to a file
await pipeline(Readable.from(track), createWriteStream("path/to/music.mp3"));
```

次に、実行します。

```python
python example.py
```

```typescript
npx tsx example.mts
```

生成された音楽が再生されます。

#### CLI

トラックを生成してファイルに保存します。

```bash
elevenlabs music compose \
  --prompt "Create an intense, fast-paced electronic track for a high-adrenaline video game scene. Use driving synth arpeggios, punchy drums, distorted bass, glitch effects, and aggressive rhythmic textures. The tempo should be fast, 130–150 bpm, with rising tension, quick transitions, and dynamic energy bursts." \
  --music-length-ms 10000 \
  --model-id music_v2_5 \
  --output music.mp3
```

`music.mp3`を開いて結果を確認します。

## コンポジションプラン

コンポジションプランは、生成したい音楽をより詳しく記述するJSONオブジェクトです。簡単なプロトタイピングにはテキストプロンプトを使用し、チャンク構造の指定、歌詞タイミングの正確な調整、複雑なアレンジが必要な場合はコンポジションプランを使用します。

#### [コンポジションプランガイド](/docs/ja/eleven-api/guides/how-to/music/composition-plans)

チャンク、スタイル、歌詞を使って曲を構成し、細かく制御する方法を学びます。

### コンポジションプランを生成する

APIを使用して、プロンプトからコンポジションプランを生成できます。

```python
from elevenlabs.client import ElevenLabs
from elevenlabs.play import play
import os
from dotenv import load_dotenv
load_dotenv()

elevenlabs = ElevenLabs(
api_key=os.getenv("ELEVENLABS_API_KEY"),
)

composition_plan = elevenlabs.music.composition_plan.create(
    prompt="Create an intense, fast-paced electronic track for a high-adrenaline video game scene. Use driving synth arpeggios, punchy drums, distorted bass, glitch effects, and aggressive rhythmic textures. The tempo should be fast, 130–150 bpm, with rising tension, quick transitions, and dynamic energy bursts.",
    music_length_ms=10000,
    model_id="music_v2_5",
)

print(composition_plan)
```

```typescript
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
import "dotenv/config";

const elevenlabs = new ElevenLabsClient();

const compositionPlan = await elevenlabs.music.compositionPlan.create({
  prompt: "Create an intense, fast-paced electronic track for a high-adrenaline video game scene. Use driving synth arpeggios, punchy drums, distorted bass, glitch effects, and aggressive rhythmic textures. The tempo should be fast, 130–150 bpm, with rising tension, quick transitions, and dynamic energy bursts.",
  musicLengthMs: 10000,
  modelId: "music_v2_5",
});

console.log(JSON.stringify(compositionPlan, null, 2));
```

上記により、次のようなコンポジションプランが生成されます。

```json
{
  "chunks": [
    {
      "text": "[Intro]",
      "durationMs": 3000,
      "positiveStyles": [
        "electronic",
        "fast-paced",
        "rising synth arpeggio",
        "glitch fx",
        "filtered noise sweep",
        "soft punchy kick building tension",
        "high adrenaline"
      ],
      "negativeStyles": ["soft pads", "melodic vocals", "ambient textures"],
      "contextAdherence": "high"
    },
    {
      "text": "[Peak Drop]",
      "durationMs": 4000,
      "positiveStyles": [
        "full punchy drums",
        "distorted bass stab",
        "aggressive rhythmic hits",
        "rapid arpeggio sequences"
      ],
      "negativeStyles": ["smooth transitions", "clean bass", "slow buildup"],
      "contextAdherence": "high"
    },
    {
      "text": "[Final Burst]",
      "durationMs": 3000,
      "positiveStyles": [
        "glitch stutter",
        "energy burst vox chopped sample",
        "quick transitions",
        "snare rolls"
      ],
      "negativeStyles": ["long reverb tails", "fadeout", "gentle melodies"],
      "contextAdherence": "high"
    }
  ]
}
```

### コンポジションプランを使う

コンポジションプランを`compose`メソッドに渡すことで、音楽を生成できます。

```python
# You can pass in composition_plan or prompt, but not both.
composition = elevenlabs.music.compose(
    composition_plan=composition_plan,
    model_id="music_v2_5",
)

play(composition)
```

```typescript
// You can pass in compositionPlan or prompt, but not both.
const composition = await elevenlabs.music.compose({
    compositionPlan,
    modelId: "music_v2_5",
});

await play(composition);
```

## 詳細情報付きで音楽を生成する

音楽を生成するたびに、プロンプトからコンポジションプランが作成されます。詳細レスポンスエンドポイントを使用すると、このプランを取得できます。

```python
track_details = elevenlabs.music.compose_detailed(
    prompt="Create an intense, fast-paced electronic track for a high-adrenaline video game scene. Use driving synth arpeggios, punchy drums, distorted bass, glitch effects, and aggressive rhythmic textures. The tempo should be fast, 130–150 bpm, with rising tension, quick transitions, and dynamic energy bursts.",
    music_length_ms=10000,
    model_id="music_v2_5",
)

print(track_details.json) # json contains composition_plan and song_metadata. The composition plan will include lyrics (if applicable)
print(track_details.filename)
# track_details.audio contains the audio bytes
```

```typescript
const trackDetails = await elevenlabs.music.composeDetailed({
  prompt: 'Create an intense, fast-paced electronic track for a high-adrenaline video game scene. Use driving synth arpeggios, punchy drums, distorted bass, glitch effects, and aggressive rhythmic textures. The tempo should be fast, 30–150 bpm, with rising tension, quick transitions, and dynamic energy bursts.',
  musicLengthMs: 10000,
  modelId: "music_v2_5",
});

console.log(JSON.stringify(trackDetails.json, null, 2)); // json contains composition_plan and song_metadata. The composition plan will include lyrics (if applicable)
console.log(trackDetails.filename);
// trackDetails.audio contains the audio bytes
```

## 著作権で保護された素材

著作権で保護された素材を含む音楽またはコンポジションプランを生成しようとすると、エラーになります。これには、バンドやミュージシャンを名前で指定することや、著作権で保護された歌詞を使用することが含まれます。

### 著作権で保護された素材を含むプロンプト

この場合、APIは代わりに使用できるプロンプトの候補を含む`bad_prompt`エラーを返します。

```python
try:
    # This will result in a bad_prompt error
    track = elevenlabs.music.compose(
        prompt="A song that sounds like 'Bohemian Rhapsody'",
        music_length_ms=10000,
        model_id="music_v2_5",
    )
  except Exception as e:
      if e.body['detail']['status'] == 'bad_prompt':
          prompt_suggestion = e.body['detail']['data']['prompt_suggestion']
          print(prompt_suggestion) # Prints: An epic rock ballad with dramatic tempo changes, operatic harmonies, and a narrative structure that blends melancholy with bursts of theatrical intensity.

          # Use the prompt suggestion to generate the track instead
```

```typescript
try {
  // This will result in a bad_prompt error
  const track = await elevenlabs.music.compose({
    prompt: "A song that sounds like 'Bohemian Rhapsody'",
    musicLengthMs: 10000,
    modelId: "music_v2_5",
  });
} catch (error) {
  if (error.body.detail.status === 'bad_prompt') {
    const promptSuggestion = error.body.detail.data.prompt_suggestion;
    console.log(promptSuggestion); // Logs: An epic rock ballad with dramatic tempo changes, operatic harmonies, and a narrative structure that blends melancholy with bursts of theatrical intensity.

    // Use the prompt suggestion to generate the track instead
  }
}
```

### 著作権で保護された素材を含むコンポジションプラン

著作権で保護された素材を使用するスタイルでコンポジションプランを生成した場合、`bad_composition_plan`エラーが返されます。音楽プロンプトと同様に、提案されたコンポジションプラン`composition_plan_suggestion`がエラー内で返されます。

> **Warning**
>
> 有害な素材を含むコンポジションプランまたはプロンプトの場合、プロンプトの候補は
> 返されません。

## 次のステップ

#### [音楽をストリーミング](/docs/ja/eleven-api/guides/how-to/music/streaming)

ファイル全体の完了を待たずに、生成された音楽をリアルタイムでストリーミングします。

#### [音楽インペインティング](/docs/ja/eleven-api/guides/how-to/music/inpainting)

既存の音楽トラックの特定セクションを変更または拡張します。

#### [APIリファレンス](/docs/ja/api-reference/music/compose)

Music APIのすべてのパラメータとレスポンス形式を確認します。