PS:安装完后没验证,先挖个坑
Musicgen是Meta推出的一个根据文字描述来生成一段音乐的项目。目前,github上7.9k星。它还可以结合一段音频(甚至是哼的歌)+文字来进行生成。单次生成最高30s。再长需要通过滑动窗口实现,取上一段生成结果的最后10s来生成接下来的20s,不断重复。用户可以通过调整描述词汇、输入的音频等来生成不同类型的音乐,比如轻松愉悦的流行音乐、激情四溢的摇滚乐、高雅典雅的古典音乐等。
模型一共有发布了4个版本:
生成结果示例:MusicGen: Simple and Controllable Music Generation (honu.io)
项目github地址:facebookresearch/audiocraft: Audiocraft is a library for audio processing and generation with deep learning. It features the state-of-the-art EnCodec audio compressor / tokenizer, along with MusicGen, a simple and controllable music generation LM with textual and melodic conditioning. (github.com)
项目huggingface modelcard:facebook/musicgen-melody · Hugging Face
1. 创建虚拟环境
conda create -n musicgen python=3.9
2. 激活
conda activate musicgen
3. 安装torch和项目
pip install 'torch>=2.0'
pip install -U audiocraft
4. 安装依赖
apt-get install ffmpeg
5. 整个小脚本 test.py
touch test.py
vim test.py #也可以只用第二行 直接创建
复制进去以下代码:
from audiocraft.models import musicgen
from audiocraft.utils.notebook import display_audio
import torch
# 第一个参数是指用哪一个模型 详见官方github
model = musicgen.MusicGen.get_pretrained('melody', device='cuda')
# 这里调整生成时长
model.set_generation_params(duration=8)
# 这里调整描述词
discriptions = [
'crazy EDM, heavy bang',
'classic reggae track with an electronic guitar solo',
'lofi slow bpm electro chill with organic samples',
'rock with saturated guitars, a heavy bass line and crazy drum break and fills.',
'earthy tones, environmentally conscious, ukulele-infused, harmonic, breezy, easygoing, organic instrumentation, gentle grooves',
]
# 测试用 只用最后一个提示词
res = model.generate(discriptions[-1] , progress=True)
display_audio(res, 32000)
运行代码:
python test.py
PS1:melody是模型的版本,musicgen一共有4个版本
PS2:第一次调用会先下载模型下来。需要魔法。
服务器没有魔法下载模型慢的解决方法:
没有魔法的话,介绍一个笨办法:用有魔法的电脑从官方huggingface把模型下载下来,传到服务器上。然后,替换你运行这段代码时他提示会把模型下载到的位置,替换掉。
下载地址:facebook/musicgen-melody at main (huggingface.co)
比如我的是这两个:
/root/.cache/torch/hub/checkpoints/b0dbef54-37d256b525.th
/root/.cache/torch/hub/checkpoints/f79af192-61305ffc49.th
经验证这个方法是ok的。
也可以直接把这写文件下到某个目录下,在加载模型的地方直接指向那个目录即可。
6. 再次运行这个小脚本:
python test.py
正常输出出来一个缓存的音频文件就没有问题啦!