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
英文地址,請注明出處:http://en.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;之后代理向目標服務器轉發請求&#…