Beatoven AI 自动生成音乐

Beatoven AI 自动生成音乐

文章目录

  • Beatoven AI 自动生成音乐
  • 一、源代码
  • 二、准备工作
    • 1. 安装 Python 环境
    • 2. 安装依赖库
  • 三、配置 API 密钥
  • 四、运行脚本
      • 示例一:使用默认参数
      • 示例二:生成一段电影预告片风格音乐(30秒)
  • 五、生成结果
  • 六、注意事项
  • 七、示例提示词(Prompt)推荐

一、源代码

import asyncio
import os
import aiohttp
import aiofiles
import argparse  # 导入 argparse 模块用于解析命令行参数BACKEND_V1_API_URL = "https://public-api.beatoven.ai/api/v1"
BACKEND_API_HEADER_KEY = "xxx"  # 嵌入提供的 API 密钥# 检查 API 密钥是否有效
if not BACKEND_API_HEADER_KEY:raise ValueError("BACKEND_API_HEADER_KEY is not set")async def compose_track(request_data, session):try:async with session.post(f"{BACKEND_V1_API_URL}/tracks/compose",json=request_data,headers={"Authorization": f"Bearer {BACKEND_API_HEADER_KEY}"},timeout=30) as response:data = await response.json()if response.status != 200 or not data.get("task_id"):raise Exception({"error": f"Composition failed: {data}"})return dataexcept aiohttp.ClientConnectionError as e:raise Exception({"error": f"Could not connect to beatoven.ai: {str(e)}"}) from eexcept aiohttp.ClientError as e:raise Exception({"error": f"HTTP error: {str(e)}"}) from eexcept Exception as e:raise Exception({"error": f"Unexpected error: {str(e)}"}) from easync def get_track_status(task_id, session):try:async with session.get(f"{BACKEND_V1_API_URL}/tasks/{task_id}",headers={"Authorization": f"Bearer {BACKEND_API_HEADER_KEY}"},timeout=30) as response:if response.status == 200:data = await response.json()return dataelse:raise Exception({"error": f"Composition failed: {await response.text()}"})except aiohttp.ClientConnectionError as e:raise Exception({"error": f"Could not connect: {str(e)}"}) from eexcept aiohttp.ClientError as e:raise Exception({"error": f"HTTP error: {str(e)}"}) from eexcept Exception as e:raise Exception({"error": f"Unexpected error: {str(e)}"}) from easync def handle_track_file(track_path: str, track_url: str, session):try:async with session.get(track_url, timeout=60) as response:if response.status == 200:async with aiofiles.open(track_path, "wb") as f:await f.write(await response.read())return {}else:raise Exception({"error": f"Download failed: {await response.text()}"})except aiohttp.ClientConnectionError as e:raise Exception({"error": f"Could not download file: {str(e)}"}) from eexcept aiohttp.ClientError as e:raise Exception({"error": f"HTTP error: {str(e)}"}) from eexcept Exception as e:raise Exception({"error": f"Unexpected error: {str(e)}"}) from easync def watch_task_status(task_id, session, interval=10):while True:track_status = await get_track_status(task_id, session)if "error" in track_status:raise Exception(track_status)print(f"Task status: {track_status}")if track_status.get("status") == "composing":await asyncio.sleep(interval)elif track_status.get("status") == "failed":raise Exception({"error": "Task failed"})else:return track_statusasync def create_and_compose(text_prompt: str, session, duration: int = 180, audio_format: str = "mp3"):track_meta = {"prompt": {"text": text_prompt},"format": audio_format,"duration": duration  # 添加时长参数}try:compose_res = await compose_track(track_meta, session)task_id = compose_res["task_id"]print(f"Started composition task with ID: {task_id}")generation_meta = await watch_task_status(task_id, session)print(generation_meta)track_url = generation_meta["meta"]["track_url"]print("Downloading track file")await handle_track_file(os.path.join(os.getcwd(), f"composed_track_3.{audio_format}"), track_url, session)print(f"Composed! You can find your track as `composed_track_3.{audio_format}`")except Exception as e:print(f"Error: {str(e)}")raiseasync def main():# 解析命令行参数parser = argparse.ArgumentParser(description='生成AI音乐')parser.add_argument('--prompt', type=str, default="我需要一个环境、平静和冥想的轨道,带有柔软的合成器垫和慢速的瑜伽",help='音乐描述文本')parser.add_argument('--duration', type=int, default=180,help='音乐时长(秒)')parser.add_argument('--format', type=str, default="mp3",choices=["mp3", "wav", "ogg"],help='音频格式')args = parser.parse_args()# 使用上下文管理器来确保会话正确关闭async with aiohttp.ClientSession() as session:await create_and_compose(args.prompt, session, args.duration, args.format)if __name__ == "__main__":# 使用 asyncio.run() 替代手动创建和管理事件循环# 这个函数会自动创建新的事件循环,运行任务,然后正确关闭事件循环try:asyncio.run(main())except KeyboardInterrupt:print("程序被用户中断")except Exception as e:print(f"发生错误: {e}")

此脚本通过调用 Beatoven AI 的接口,根据你的提示语(prompt)生成符合需求的背景音乐,并将其下载保存到本地。支持设置音乐时长、输出格式等参数。

PS:根据 Beatoven AI 分别做了两份JSON文件,可供Promot生成的AI进行参考以给出更符合 Beatoven AI 规范的promot


二、准备工作

1. 安装 Python 环境

确保你已经安装了 Python 3.7 及以上版本。可在终端输入以下命令检查:

python --version

如果未安装,请访问 https://www.python.org/ 下载安装。

2. 安装依赖库

进入脚本所在目录,执行以下命令安装所需的第三方依赖:

pip install aiohttp aiofiles

三、配置 API 密钥

在脚本中已经内嵌了一条 API 密钥:
申请网页:https://sync.beatoven.ai/workspace

BACKEND_API_HEADER_KEY = "xxx"

⚠️ 建议你替换为你自己的密钥,以防止密钥失效或滥用。


四、运行脚本

脚本支持命令行参数,你可以灵活指定以下选项:

  • --prompt: 音乐描述(提示语)
  • --duration: 音乐时长(单位:秒,默认 180)
  • --format: 音频格式(mp3 / wav / ogg)

示例一:使用默认参数

python beatoven_music_gen.py

等同于执行:

python beatoven_music_gen.py --prompt "我需要一个环境、平静和冥想的轨道,带有柔软的合成器垫和慢速的瑜伽" --duration 180 --format mp3

示例二:生成一段电影预告片风格音乐(30秒)

python beatoven_music_gen.py --prompt "史诗、紧张的电影配乐,包含弦乐和打击乐,快速节奏" --duration 30 --format wav

五、生成结果

生成完成后,音乐文件将被保存在当前工作目录中,文件名形如:

composed_track_3.mp3

控制台会输出如下内容:

Started composition task with ID: xxxxxxxx
Task status: composing
...
Task status: success
Downloading track file
Composed! You can find your track as `composed_track_3.mp3`

六、注意事项

  • 生成时间较长:通常在 10~60 秒不等,取决于时长与复杂度。

  • 提示词要尽量符合规范:参考 Beatoven 官方推荐结构(如:风格、情绪、节奏、使用场景等)。

  • 不支持歌词、人声指令:但可包含人声氛围元素。

  • 最大时长限制:音乐最大为 15 分钟(900 秒),最短为 10 秒。

  • 可能会有如下警告,但是不会影响音频生成

  •   Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000015DA57DF9D0>Traceback (most recent call last):File "D:\anaconda3\envs\Daily\lib\asyncio\proactor_events.py", line 116, in __del__self.close()File "D:\anaconda3\envs\Daily\lib\asyncio\proactor_events.py", line 108, in closeself._loop.call_soon(self._call_connection_lost, None)File "D:\anaconda3\envs\Daily\lib\asyncio\base_events.py", line 719, in call_soonself._check_closed()File "D:\anaconda3\envs\Daily\lib\asyncio\base_events.py", line 508, in _check_closedraise RuntimeError('Event loop is closed')RuntimeError: Event loop is closedTraceback (most recent call last):File "D:\anaconda3\envs\Daily\lib\asyncio\proactor_events.py", line 116, in __del__self.close()File "D:\anaconda3\envs\Daily\lib\asyncio\proactor_events.py", line 108, in closeself._loop.call_soon(self._call_connection_lost, None)File "D:\anaconda3\envs\Daily\lib\asyncio\base_events.py", line 719, in call_soonself._check_closed()File "D:\anaconda3\envs\Daily\lib\asyncio\base_events.py", line 508, in _check_closedraise RuntimeError('Event loop is closed')RuntimeError: Event loop is closed
    

七、示例提示词(Prompt)推荐

用途示例
YouTube vlog快乐、轻快,使用原声吉他和打击乐,中速节奏,适合晨间Vlog
游戏原声电子风格,紧张氛围,快速节奏,适合战斗场景
冥想音乐氛围风格、平静情绪,包含合成器音色,慢速节奏

prompt_guidelines.json

{"fields": [{"name": "genre","description": "Specify the music style, e.g., Ambient, Cinematic, Lo-fi, Electronic, Rock, Jazz, Hip-hop."},{"name": "instruments","description": "List the instruments or sounds to include, e.g., Piano, Guitar, Drums, Synth Pads, Electronic FX."},{"name": "mood","description": "Describe the emotion you want, e.g., Calm, Energetic, Melancholic, Tense, Uplifting."},{"name": "tempo","description": "Use descriptive terms rather than exact BPM, e.g., Slow, Medium, Fast."},{"name": "use_case","description": "Explain the intended use, e.g., Podcast Background, Film Score, Game OST, YouTube Video."},{"name": "duration","description": "Specify length, e.g., 30 seconds, 1 minute, 2 minutes; default is 1 minute."}],"limitations": ["No transitions or crossfades","No foley or sound effects","No vocals","Avoid technical music terms (scales, chords, exact BPM)"],"suggestions": ["Keep prompts concise and clear","Avoid jargon to improve generation accuracy","Use simple adjectives for mood and tempo"],"example": {"genre": "Ambient","instruments": ["Soft Synth Pads"],"mood": "Calm","tempo": "Slow","use_case": "Yoga Session","duration": "2 minutes"}
}

promot_guidelines_more.json

{"prompt": {"genre": {"description": "Specify the genre of music you want to create.","type": "string","examples": ["Ambient","Cinematic","Lo-fi","Electronic","Rock","Jazz","Hip-hop"]},"instruments": {"description": "Mention the instruments you'd like featured (traditional or electronic).","type": "array","items": {"type": "string","examples": ["piano","guitar","drums","synthesizer","pads"]}},"mood": {"description": "Describe the mood or emotion you want the music to convey.","type": "string","examples": ["Happy","Sad","Tense","Calm","Uplifting","Dark"]},"tempo": {"description": "Choose a descriptive tempo rather than specific BPM values.","type": "string","enum": ["Slow","Medium","Fast","Upbeat","Chill","Laidback"],"notes": "Avoid numeric BPM to prevent misinterpretation."},"use_case": {"description": "Specify the intended use of the music.","type": "string","examples": ["Podcast background","Film score","Game soundtrack","YouTube video"]},"duration": {"description": "Desired track length in seconds or minutes.","type": "string","pattern": "^\\d+\\s?(s|seconds|m|minutes)$","default": "1m","constraints": {"min": "10s","max": "15m","optimum_range": "15s–2.5m"}}},"limitations": {"instruments": {"notes": "Some rare/specific instruments may not be available. You can download stems for individual tracks."},"transitions": {"supported": false,"notes": "Smooth transitions not currently supported."},"sound_effects_foley": {"supported": false,"notes": "Cannot generate sound effects or foley."},"vocals": {"supported": "instrumental layers only","notes": "No lyrics or voiceover generation."},"loops": {"guaranteed": false,"notes": "Some output may loop, but not guaranteed."},"key_scales_time_signatures": {"supported": false,"notes": "Avoid specifying musical theory terms like ‘F#’, ‘minor’, ‘6/8’, etc."}},"examples": [{"prompt": "Ambient, calm, meditative track with soft synth pads, slow tempo, for a yoga session.","duration": "1m"},{"prompt": "Cinematic, epic orchestral piece, fast tempo, heroic mood, 30s, for a movie trailer."},{"prompt": "Lo-fi, chill track with jazzy guitar, relaxed tempo, nostalgic mood, 2m, for a study playlist."},{"prompt": "Happy, upbeat music with acoustic guitar and light percussion, medium tempo, 1.5m, for a morning vlog."}]
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/81500.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/81500.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

笔试专题(十四)

文章目录 mari和shiny题解代码 体操队形题解代码 二叉树中的最大路径和题解代码 mari和shiny 题目链接 题解 1. 可以用多状态的线性dp 2. 细节处理&#xff1a;使用long long 存储个数 3. 空间优化&#xff1a;只需要考虑等于’s’&#xff0c;‘sh’&#xff0c;shy’的情况…

LeetCode —— 94. 二叉树的中序遍历

&#x1f636;‍&#x1f32b;️&#x1f636;‍&#x1f32b;️&#x1f636;‍&#x1f32b;️&#x1f636;‍&#x1f32b;️Take your time ! &#x1f636;‍&#x1f32b;️&#x1f636;‍&#x1f32b;️&#x1f636;‍&#x1f32b;️&#x1f636;‍&#x1f32b;️…

conda相关操作

安装torch 直接使用conda install torch1.12.0会报错&#xff0c;因为 Conda 通常使用 pytorch 作为包名&#xff08;而非 torch&#xff09; 正确使用方法&#xff1a; conda install pytorch1.12.0 -c pytorch使用 pip 安装 pip install torch1.12.0在 Conda 中查看可安装…

【Java面试笔记:进阶】26.如何监控和诊断JVM堆内和堆外内存使用?

监控和诊断JVM内存使用是优化性能和解决内存问题的关键。 1.JVM内存监控与诊断方法 1.图形化工具 JConsole:提供图形化界面,可直接连接到Java进程,查看内存使用情况。VisualVM:功能强大的图形化工具,但注意从Oracle JDK 9开始不再包含在JDK安装包中。Java Mission Contr…

AVIOContext 再学习

这个目前阶段用的不多&#xff0c;暂时不要花费太多精力。 url 的格式不同&#xff0c;使用的传输层协议也不同。这块看代码还没看到自己想的这样。 目前看的信息是&#xff1a;avformatContext 的 io_open 回调函数 在默认情况下叫 io_open_default&#xff0c;在解复用的 av…

在Java项目中实现本地语音识别与热点检测,并集成阿里云智能语音服务

引言 随着语音交互技术的发展&#xff0c;如何高效地处理用户的语音输入成为许多应用的重要课题。本文将详细介绍如何在一个Java项目中同时实现&#xff1a; 基于Vosk的本地语音识别&#xff1a;无需调用云端API即可完成语音到文本的转换。本地热点语音内容识别&#xff1a;对…

第15章 对API的身份验证和授权

第15章 对API的身份验证和授权 在构建RESTful API时,确保只有经过身份验证和授权的用户才能访问特定资源是至关重要的。身份验证是确认用户身份的过程,而授权则是决定用户是否有权访问特定资源的过程。在本章中,我们将详细探讨如何在ASP.NET Core Web API中实现身份验证和授…

asp.net客户管理系统批量客户信息上传系统客户跟单系统crm

# crm-150708 客户管理系统批量客户信息上传系统客户跟单系统 # 开发背景 本软件是给郑州某企业管理咨询公司开发的客户管理系统软件 # 功能 1、导入客户数据到系统 2、批量将不同的客户分配给不同的业务员跟进 3、可以对客户数据根据紧急程度标记不同的颜色&#xff0c…

深入理解现代JavaScript:从ES6+语法到Fetch API

引言 JavaScript作为Web开发的基石语言&#xff0c;近年来经历了翻天覆地的变化。ES6(ECMAScript 2015)的发布带来了革命性的新特性&#xff0c;而现代浏览器提供的API也让前端开发变得更加强大和高效。本文将深入探讨ES6核心语法、DOM操作优化技巧以及使用Fetch API进行异步请…

仙盟创梦IDE-智能编程,C#判断数组中是否存在key

一、net4 net core版本 使用LINQ的Contains方法 string[] array { "apple", "banana", "cherry" };string key "banana";bool exists array.Contains(key);if (exists){Console.WriteLine($"数组中存在键 {key}");}else…

360驱动大师v2.0(含网卡版)驱动工具软件下载及安装教程

1.软件名称&#xff1a;360驱动大师 2.软件版本&#xff1a;2.0 3.软件大小&#xff1a;218 MB 4.安装环境&#xff1a;win7/win10/win11 5.下载地址&#xff1a; https://www.kdocs.cn/l/cdZMwizD2ZL1?RL1MvMTM%3D 提示&#xff1a;先转存后下载&#xff0c;防止资源丢失&…

2025年- H22-Lc130-206. 反转链表(链表)---java版

1.题目描述 2.思路 使用迭代法 (1)定义一个前指针 (2)然后定义两个变量 curr&#xff08;head&#xff09;&#xff0c;curr.next。 (3)curr和curr.next交换位置&#xff08;只要当前指针不为空&#xff0c;执行两两交换&#xff09; 3.代码实现 /*** Definition for singly-…

机器学习常用评价指标

1. 指标说明 (1) AccuracyClassification&#xff08;准确率&#xff09; • 计算方式&#xff1a;accuracy_score(y_true, y_pred) • 作用&#xff1a; 衡量模型正确预测的样本比例&#xff08;包括所有类别&#xff09;。 公式&#xff1a; Accuracy TP TN TP TN FP…

CGI(Common Gateway Interface)协议详解

CGI&#xff08;通用网关接口&#xff09;是一种标准化的协议&#xff0c;定义了 Web服务器 与 外部程序&#xff08;如脚本或可执行文件&#xff09;之间的数据交互方式。它允许服务器动态生成网页内容&#xff0c;而不仅仅是返回静态文件。 1. CGI 的核心作用 动态内容生成&a…

2025.4.29总结

工作&#xff1a;最近手头活变得多起来了&#xff0c;毕竟要测两个版本&#xff0c;有时候觉得很奇怪&#xff0c;活少的时候&#xff0c;又想让别人多分点活&#xff0c;活多的时候&#xff0c;又会有些许不自然。这种反差往往伴随着项目的节奏&#xff0c;伴随着两个极端。所…

【KWDB 创作者计划】技术解读:多模架构、高效时序数据处理与分布式实现

技术解读&#xff1a;多模架构、高效时序数据处理与分布式实现 一、多模架构1.1 架构概述1.2 源码分析1.3 实现流程 二、高效时序数据处理2.1 处理能力概述2.2 源码分析2.3 实现流程 三、分布式实现3.1 分布式特性概述3.2 源码分析3.3 实现流程 四、总结 在当今数据爆炸的时代&…

# 前后端分离象棋对战项目开发记录

1. **结构清晰**&#xff1a;使用更直观的标题、分段和列表&#xff0c;增强可读性。 2. **视觉美观**&#xff1a;添加Markdown格式化&#xff08;如代码块、加粗、斜体&#xff09;&#xff0c;并建议配色和排版风格。 3. **内容精炼**&#xff1a;精简冗余表述&#xff0c;突…

HarmonyOS NEXT 诗词元服务项目开发上架全流程实战(一、项目介绍及实现效果)

在当今数字化时代&#xff0c;如何让传统文化与现代科技相结合&#xff0c;成为了一个值得思考的问题。诗词作为中国传统文化的重要组成部分&#xff0c;承载着丰富的历史信息和文化内涵。为了让更多人了解和欣赏诗词的魅力&#xff0c;我们决定开发一款基于HarmonyOS NEXT的诗…

linux jounery 日志相关问题

/var/log 目录 是 Linux 系统中存放各种日志文件的标准位置。 这些日志文件记录了系统及其服务的运行状态。 日志文件来源 系统日志 由 syslog 或 systemd-journald&#xff08;如果使用 systemd 的话&#xff09;等日志服务生成。记录内核消息和各种系统事件&#xff0c;例如…

JavaWeb学习打卡-Day7-正向代理、反向代理、Nginx

正向代理 概念&#xff1a;正向代理是一个位于客户端和目标服务器之间的代理服务器&#xff08;中间服务器&#xff09;。为了从目标服务器取得内容&#xff0c;客户端向代理服务器发送一个请求&#xff0c;并且指定目标服务器&#xff0c;之后代理向目标服务器转发请求&#…