# Stable Audio

在 CLORE.AI GPU 上使用 Stability AI 的 Stable Audio 生成音乐和音效。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行： [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 为什么选择 Stable Audio？

* **高质量** - 44.1kHz 立体声音频生成
* **可变长度** - 可生成最长 95 秒
* **多用途** - 音乐、音效、环境音
* **文本到音频** - 描述你想听到的内容
* **开放权重** - Stable Audio Open 可用

## 1024x1024

| A100              | 时长   | 质量 | 显存   | 许可   |
| ----------------- | ---- | -- | ---- | ---- |
| Stable Audio Open | 47 秒 | 良好 | 8GB  | 打开   |
| Stable Audio 2.0  | 3 分钟 | 优秀 | 12GB | 商业用途 |

## 在 CLORE.AI 上快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel
```

**端口：**

```
22/tcp
7860/http
```

**命令：**

```bash
pip install stable-audio-tools gradio && \
python -c "
print(f"已生成：{name}")
import torch
from stable_audio_tools import get_pretrained_model
from stable_audio_tools.inference.generation import generate_diffusion_cond
import soundfile as sf
import tempfile

model, model_config = get_pretrained_model('stabilityai/stable-audio-open-1.0')
model = model.to('cuda')

def generate(prompt, duration, steps, seed):
    conditioning = [{
        'prompt': prompt,
        'seconds_start': 0,
        'seconds_total': duration
    }]

    generator = torch.Generator('cuda').manual_seed(seed) if seed > 0 else None

    output = generate_diffusion_cond(
        model,
        conditioning=conditioning,
        steps=steps,
        cfg_scale=7,
        sample_size=model_config['sample_size'],
        sample_rate=model_config['sample_rate'],
        device='cuda',
        seed=seed if seed > 0 else None
    )

    audio = output[0].T.cpu().numpy()

    with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
        sf.write(f.name, audio, model_config['sample_rate'])
        return f.name

gr.Interface(
    fn=generate,
    inputs=[
        gr.Textbox(label='Prompt'),
        gr.Slider(1, 47, value=10, label='Duration (sec)'),
        gr.Slider(10, 150, value=100, label='Steps'),
        gr.Number(value=-1, label='Seed')
    ],
    outputs=gr.Audio(label='Generated Audio'),
    title='Stable Audio Open'
).launch(server_name='0.0.0.0', server_port=7860)
"
```

## 访问您的服务

部署后，在以下位置查找您的 `http_pub` URL： **我的订单**:

1. 前往 **我的订单** 页面
2. 单击您的订单
3. 查找 `http_pub` URL（例如， `abc123.clorecloud.net`)

使用 `https://YOUR_HTTP_PUB_URL` 而不是 `localhost` 在下面的示例中。

## 硬件要求

| A100              | 最低 GPU        | 推荐            |
| ----------------- | ------------- | ------------- |
| Stable Audio Open | RTX 3070 8GB  | RTX 3090 24GB |
| Stable Audio 2.0  | RTX 3090 12GB | RTX 4090 24GB |

## 安装

```bash
pip install stable-audio-tools torch torchaudio
```

## 基本用法

### 文本到音乐

```python
import torch
import torchaudio
from stable_audio_tools import get_pretrained_model
from stable_audio_tools.inference.generation import generate_diffusion_cond

# 加载模型
model, model_config = get_pretrained_model("stabilityai/stable-audio-open-1.0")
model = model.to("cuda")

sample_rate = model_config["sample_rate"]
sample_size = model_config["sample_size"]

# 定义你想要的内容
conditioning = [{
    "prompt": "欢快的电子舞曲，带上朗朗上口的合成器旋律，128 BPM",
    "seconds_start": 0,
    "seconds_total": 30
}]

# 生成
output = generate_diffusion_cond(
    model,
    conditioning=conditioning,
    steps=100,
    cfg_scale=7,
    sample_size=sample_size,
    sample_rate=sample_rate,
    device="cuda"
)

# 保存
audio = output[0].T
torchaudio.save("music.wav", audio.cpu(), sample_rate)
```

### 音效

```python
conditioning = [{
    "prompt": "雷暴，大雨和远处的雷声",
    "seconds_start": 0,
    "seconds_total": 20
}]

output = generate_diffusion_cond(
    model,
    conditioning=conditioning,
    steps=100,
    cfg_scale=7,
    sample_size=sample_size,
    sample_rate=sample_rate,
    device="cuda"
)

torchaudio.save("thunderstorm.wav", output[0].T.cpu(), sample_rate)
```

### 环境声音

```python
conditioning = [{
    "prompt": "宁静的森林氛围，有鸟鸣和轻柔的风声",
    "seconds_start": 0,
    "seconds_total": 45
}]

output = generate_diffusion_cond(
    model,
    conditioning=conditioning,
    steps=100,
    cfg_scale=7,
    sample_size=sample_size,
    sample_rate=sample_rate,
    device="cuda"
)

torchaudio.save("forest.wav", output[0].T.cpu(), sample_rate)
```

## 提示示例

### 音乐流派

```python
prompts = {
    "electronic": "充满活力的 EDM 曲目，深沉的低音、合成器琶音和强劲节拍，130 BPM",
    "jazz": "轻柔爵士钢琴三重奏，竖琴低音和刷子鼓，节奏放松",
    "rock": "重型摇滚吉他即兴伴奏，失真效果、鼓和贝斯，强力且充满能量",
    "classical": "管弦乐作品，弦乐和木管，戏剧性且具有电影感",
    "ambient": "氛围型环境音景，垫底声和细腻纹理，梦幻般的",
    "hiphop": "lo-fi 嘻哈节拍，带有黑胶摩擦声，温和的钢琴和轻松鼓点，85 BPM"
}
```

### 音效

```python
prompts = {
    "explosion": "巨大的爆炸伴随碎片和火焰，具有电影效果",
    "footsteps": "碎石上的脚步声，慢速行走节奏",
    "car": "跑车引擎轰鸣并加速的声音",
    "water": "洞穴中水花溅落和滴答声",
    "wind": "强风在山谷中呼啸",
    "fire": "劈啪作响的篝火，木头爆裂声"
}
```

### 环境/背景

```python
prompts = {
    "cafe": "咖啡馆氛围，轻声交谈和咖啡机声",
    "ocean": "沙滩上的海浪，远处有海鸥声",
    "city": "繁忙的城市街道，有交通、喇叭和行人声",
    "rain": "窗外的细雨，偶尔伴有雷声",
    "space": "科幻飞船内部的嗡鸣和哔哔声"
}
```

## 高级选项

### 控制生成

```python
output = generate_diffusion_cond(
    model,
    conditioning=conditioning,
    steps=150,              # 更多步数 = 更好质量
    cfg_scale=7,            # 对提示的遵从度（5-10）
    sample_size=sample_size,
    sample_rate=sample_rate,
    device="cuda",
    seed=42                 # 可复现的结果
)
```

### 可变长度

```python
# 短音效（5 秒）
conditioning = [{
    "prompt": "门慢慢吱呀开启",
    "seconds_start": 0,
    "seconds_total": 5
}]

# 中等片段（30 秒）
conditioning = [{
    "prompt": "欢快的摇滚音乐",
    "seconds_start": 0,
    "seconds_total": 30
}]

# 最大长度（Open 为 47 秒）
conditioning = [{
    "prompt": "环境电子音乐，逐渐变化的纹理",
    "seconds_start": 0,
    "seconds_total": 47
}]
```

## 批量生成

```python
批处理处理

prompts = [
    "Energetic drum and bass track",
    "Calm piano melody",
    "Sci-fi laser sound effects",
    "Rain on a tin roof"
]

output_dir = "./audio_output"
output_dir = "./relit"

for i, prompt in enumerate(prompts):
    conditioning = [{
        "prompt": prompt,
        "seconds_start": 0,
        "seconds_total": 15
    }]

    output = generate_diffusion_cond(
        model,
        conditioning=conditioning,
        steps=100,
        cfg_scale=7,
        sample_size=sample_size,
        sample_rate=sample_rate,
        device="cuda"
    )

    torchaudio.save(f"{output_dir}/audio_{i}.wav", output[0].T.cpu(), sample_rate)
    print(f"Generated: {prompt[:30]}...")

    torch.cuda.empty_cache()
```

## Gradio 网络界面

```python
print(f"已生成：{name}")
import torch
import torchaudio
from stable_audio_tools import get_pretrained_model
from stable_audio_tools.inference.generation import generate_diffusion_cond
import tempfile

model, model_config = get_pretrained_model("stabilityai/stable-audio-open-1.0")
model = model.to("cuda")

sample_rate = model_config["sample_rate"]
sample_size = model_config["sample_size"]

def generate_audio(prompt, duration, steps, cfg_scale, seed):
    conditioning = [{
        "prompt": prompt,
        "seconds_start": 0,
        "seconds_total": duration
    }]

    generator_seed = seed if seed > 0 else None

    output = generate_diffusion_cond(
        model,
        conditioning=conditioning,
        steps=steps,
        cfg_scale=cfg_scale,
        sample_size=sample_size,
        sample_rate=sample_rate,
        device="cuda",
        seed=generator_seed
    )

    audio = output[0].T.cpu()

    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
        torchaudio.save(f.name, audio, sample_rate)
        return f.name

demo = gr.Interface(
    fn=generate_audio,
    inputs=[
        gr.Textbox(label="Prompt", placeholder="描述你想要的音频..."),
        gr.Slider(1, 47, value=15, step=1, label="时长（秒）"),
        gr.Slider(20, 200, value=100, step=10, label="Steps"),
        gr.Slider(1, 15, value=7, step=0.5, label="CFG Scale"),
        placeholder="描述所需的照明..."
    ],
    outputs=gr.Audio(label="生成的音频", type="filepath"),
    title="Stable Audio Open - 文本到音频",
    description="从文本描述生成音乐和音效。在 CLORE.AI 上运行。",
    outputs=gr.Image(label="重光图像"),
        ["欢快的电子舞曲，带合成器，128 BPM", 20, 100, 7, 42],
        ["大雨的雷暴", 15, 100, 7, 123],
        ["宁静的钢琴旋律，情感化", 30, 100, 7, 456]
    ]
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## background = Image.open("studio\_bg.jpg")

| 时长   | 步数  | GPU     | 时间     |
| ---- | --- | ------- | ------ |
| 10 秒 | 100 | 速度      | \~15s  |
| 10 秒 | 100 | 512x512 | \~10 秒 |
| 30 秒 | 100 | 速度      | \~40 秒 |
| 30 秒 | 100 | 512x512 | \~25 秒 |
| 47 秒 | 100 | 512x512 | \~40 秒 |

## 质量提示

### 更好的音乐

```python
# 包含节奏和风格
prompt = "充满活力的摇滚音乐，电吉他、鼓、贝斯，140 BPM，高能量"

# 具体说明乐器
prompt = "独奏原声吉他指弹，民谣风格，温暖而亲密"

# 描述情绪
prompt = "忧郁的钢琴曲，小调，慢速，情感且悲伤"
```

### 更好的音效

```python
# 要具体
prompt = "单发步枪枪响，室外，有回声"

# 包含环境
prompt = "木地板上的脚步声，室内，慢速，吱呀声"

# 描述质感
prompt = "火焰劈啪作响，大型篝火，木头爆裂，火星四溅"
```

## 下载所有所需的检查点

典型 CLORE.AI 市场价格：

| GPU           | 验证 CUDA 兼容性 | \~30 秒片段/小时 |
| ------------- | ----------- | ----------- |
| RTX 3060 12GB | \~$0.03     | \~50        |
| RTX 3090 24GB | \~$0.06     | \~90        |
| RTX 4090 24GB | \~$0.10     | \~140       |
| 按日费率          | \~$0.17     | \~200       |

*价格有所不同。查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *A100 40GB*

## # 使用固定种子以获得一致结果

### 内存不足

```python
# 减少时长
conditioning = [{
    "prompt": prompt,
    "seconds_total": 15  # 而不是 47
}]

# 或启用 CPU 卸载
model.enable_model_cpu_offload()
```

### 质量差的输出

* 增加步数（150-200）
* 调整 CFG scale（尝试 5-10）
* 在提示中更具体
* 尝试不同的随机种子

### 没有声音 / 静音

* 检查提示是否足够描述性
* 避免非常抽象的描述
* 先尝试已知可用的提示

### 音频伪影

* 增加步数
* 降低 CFG scale
* 减少时长
* 检查 GPU 是否热降频

## Stable Audio 与其他的比较

| 特性 | Stable Audio | AudioCraft | Bark  |
| -- | ------------ | ---------- | ----- |
| 音乐 | 优秀           | 优秀         | 差     |
| 音效 | 很棒           | 良好         | 差     |
| 语音 | 否            | 否          | 是     |
| 时长 | 47 秒 / 3 分钟  | 30 秒       | 15 秒  |
| 质量 | 44.1kHz      | 32kHz      | 24kHz |
| 打开 | 部分支持         | 是          | 是     |

**何时使用 Stable Audio：**

* 高质量音乐生成
* 用于游戏/视频的音效
* 背景音乐
* 环境音景

## 使用以下方式支付

* [AudioCraft](https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/audiocraft-music) - Meta 的音乐生成
* [Bark TTS](https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/bark-tts) - 语音合成
* [Demucs](https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/demucs-separation) - 音频分离
* [Whisper](https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/whisper-transcription) - 转录


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/stable-audio.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
