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."}]
}