Skip to content

Commit 77028bd

Browse files
techpro-aimlapigitbook-bot
authored andcommitted
GITBOOK-359: docs: add an example to music-01
1 parent 51b1830 commit 77028bd

1 file changed

Lines changed: 235 additions & 3 deletions

File tree

‎docs/api-references/music-models/MiniMax/music-01.md‎

Lines changed: 235 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,248 @@ If you don’t have an API key for the AI/ML API yet, feel free to use our [Quic
1818

1919
### Generate a music sample
2020

21-
This endpoint creates and sends a music generation task to the server — and returns a generation ID and the task status.
21+
This endpoint uploads a reference music piece to the server, analyzes it, and returns identifiers for the voice and/or instrumental patterns to use later.
2222

2323
{% openapi src="music-01-pair.json" path="/v2/generate/audio/minimax/upload" method="post" %}
2424
[music-01-pair.json](music-01-pair.json)
2525
{% endopenapi %}
2626

27-
### Retrieve the generated music sample from the server <a href="#retrieve-the-generated-video-from-the-server" id="retrieve-the-generated-video-from-the-server"></a>
27+
### Generate music sample <a href="#retrieve-the-generated-video-from-the-server" id="retrieve-the-generated-video-from-the-server"></a>
2828

29-
After sending a request for music generation, this task is added to the queue. Based on the service's load, the generation can be completed in 50-60 seconds or take a bit more.
29+
This endpoint generates a new music piece based on the voice and/or instrumental pattern identifiers obtained from the first endpoint above.\
30+
The generation can be completed in 50-60 seconds or take a bit more.
3031

3132
{% openapi src="music-01.json" path="/v2/generate/audio/minimax/generate" method="post" %}
3233
[music-01.json](music-01.json)
3334
{% endopenapi %}
35+
36+
## Quick Code Example
37+
38+
Here is an example of generation an audio file based on a sample and a prompt using the music model **music-01**.
39+
40+
{% tabs %}
41+
{% tab title="Python" %}
42+
{% code overflow="wrap" %}
43+
```python
44+
import requests
45+
46+
# Insert your AI/ML API key here:
47+
aimlapi_key = "<YOUR_AIMLAPI_KEY>"
48+
49+
# Input data
50+
audio_url = "https://tand-dev.github.io/audio-hosting/spinning-head-271171.mp3"
51+
file_name = "spinning-head-271171.mp3"
52+
purpose = "song" # Possible values: 'song', 'voice', 'instrumental'
53+
54+
55+
def upload_reference_file():
56+
"""Download file from URL and upload it to AIML API"""
57+
58+
url = "https://api.aimlapi.com/v2/generate/audio/minimax/upload"
59+
60+
try:
61+
# Step 1: Download the file
62+
response = requests.get(audio_url)
63+
response.raise_for_status()
64+
65+
# Step 2: Upload to AIML API
66+
payload = {"purpose": purpose}
67+
files = {"file": (file_name, response.content, "audio/mpeg")}
68+
headers = {"Authorization": f"Bearer {aimlapi_key}"}
69+
70+
upload_response = requests.post(url, headers=headers, files=files, data=payload)
71+
upload_response.raise_for_status()
72+
73+
data = upload_response.json()
74+
print("Upload successful:", data)
75+
return data # return JSON with file ids
76+
77+
except requests.exceptions.RequestException as error:
78+
print(f"Error during upload: {error}")
79+
return None
80+
81+
82+
def generate_audio(voice_id=None, instrumental_id=None):
83+
"""Send audio generation request and save result"""
84+
85+
url = "https://api.aimlapi.com/v2/generate/audio/minimax/generate"
86+
lyrics = (
87+
"##Side by side, through thick and thin, \n\n"
88+
"With a laugh, we always win. \n\n"
89+
"Storms may come, but we stay true, \n\n"
90+
"Friends forever—me and you!##"
91+
)
92+
93+
payload = {
94+
"refer_voice": voice_id,
95+
"refer_instrumental": instrumental_id,
96+
"lyrics": lyrics,
97+
"model": "music-01",
98+
}
99+
headers = {
100+
"Content-Type": "application/json",
101+
"Authorization": f"Bearer {aimlapi_key}",
102+
}
103+
104+
response = requests.post(url, headers=headers, json=payload)
105+
response.raise_for_status()
106+
107+
audio_hex = response.json()["data"]["audio"]
108+
decoded_hex = bytes.fromhex(audio_hex)
109+
110+
out_name = "generated_audio.mp3"
111+
with open(out_name, "wb") as f:
112+
f.write(decoded_hex)
113+
114+
print(f"Generated audio saved as {out_name}")
115+
116+
117+
def main():
118+
uploaded = upload_reference_file()
119+
if not uploaded:
120+
return
121+
122+
# Extract IDs depending on purpose
123+
voice_id = uploaded.get("voice_id")
124+
instrumental_id = uploaded.get("instrumental_id")
125+
126+
generate_audio(voice_id, instrumental_id)
127+
128+
129+
if __name__ == "__main__":
130+
main()
131+
132+
```
133+
{% endcode %}
134+
{% endtab %}
135+
136+
{% tab title="JavaScript" %}
137+
{% code overflow="wrap" %}
138+
```javascript
139+
import { writeFile } from "node:fs/promises";
140+
import { Blob } from "node:buffer";
141+
142+
// Insert your AI/ML API key here:
143+
const API_KEY = "<YOUR_AIMLAPI_KEY>";
144+
145+
// Input data
146+
const AUDIO_URL = "https://tand-dev.github.io/audio-hosting/spinning-head-271171.mp3";
147+
const FILE_NAME = "spinning-head-271171.mp3";
148+
const PURPOSE = "song"; // Possible values: 'song', 'voice', 'instrumental'
149+
150+
// Download file from URL and upload it to AIML API
151+
async function uploadReferenceFile() {
152+
const uploadUrl = "https://api.aimlapi.com/v2/generate/audio/minimax/upload";
153+
154+
try {
155+
// Step 1: Download the file
156+
const response = await fetch(AUDIO_URL);
157+
if (!response.ok) throw new Error(`Failed to download file: ${response.status}`);
158+
159+
const arrayBuffer = await response.arrayBuffer();
160+
const fileBlob = new Blob([arrayBuffer], { type: "audio/mpeg" });
161+
162+
// Step 2: Upload to AIML API
163+
const formData = new FormData();
164+
formData.append("purpose", PURPOSE);
165+
formData.append("file", fileBlob, FILE_NAME);
166+
167+
const uploadResponse = await fetch(uploadUrl, {
168+
method: "POST",
169+
headers: {
170+
Authorization: `Bearer ${API_KEY}`,
171+
// Content-Type should not be set manually for FormData
172+
},
173+
body: formData,
174+
});
175+
176+
if (!uploadResponse.ok) {
177+
const text = await uploadResponse.text();
178+
throw new Error(`Upload failed ${uploadResponse.status}: ${text}`);
179+
}
180+
181+
const data = await uploadResponse.json();
182+
console.log("Upload successful:", data);
183+
return data; // JSON with file ids
184+
185+
} catch (err) {
186+
console.error("Error during upload:", err.message);
187+
return null;
188+
}
189+
}
190+
191+
// Send audio generation request and save result
192+
async function generateAudio(voiceId = null, instrumentalId = null) {
193+
const url = "https://api.aimlapi.com/v2/generate/audio/minimax/generate";
194+
const lyrics = `
195+
##Side by side, through thick and thin,
196+
With a laugh, we always win.
197+
Storms may come, but we stay true,
198+
Friends forever—me and you!##
199+
`.trim();
200+
201+
const payload = {
202+
refer_voice: voiceId,
203+
refer_instrumental: instrumentalId,
204+
lyrics,
205+
model: "music-01",
206+
};
207+
208+
const res = await fetch(url, {
209+
method: "POST",
210+
headers: {
211+
"Content-Type": "application/json",
212+
Authorization: `Bearer ${API_KEY}`,
213+
},
214+
body: JSON.stringify(payload),
215+
});
216+
217+
if (!res.ok) {
218+
const text = await res.text();
219+
throw new Error(`Generation failed ${res.status}: ${text}`);
220+
}
221+
222+
const data = await res.json();
223+
const audioHex = data?.data?.audio;
224+
if (!audioHex) throw new Error("No audio hex in response");
225+
226+
const audioBuffer = Buffer.from(audioHex, "hex");
227+
const outName = "generated_audio.mp3";
228+
await writeFile(outName, audioBuffer);
229+
console.log(`Generated audio saved as ${outName}`);
230+
}
231+
232+
// Main function
233+
async function main() {
234+
const uploaded = await uploadReferenceFile();
235+
if (!uploaded) return;
236+
237+
// Extract IDs depending on purpose
238+
const voiceId = uploaded.voice_id;
239+
const instrumentalId = uploaded.instrumental_id;
240+
241+
await generateAudio(voiceId, instrumentalId);
242+
}
243+
244+
main();
245+
```
246+
{% endcode %}
247+
{% endtab %}
248+
{% endtabs %}
249+
250+
<details>
251+
252+
<summary>Response</summary>
253+
254+
{% code overflow="wrap" %}
255+
```json5
256+
Upload successful: {'voice_id': 'vocal-2025082518145625-6XW9wCOF', 'instrumental_id': 'instrumental-2025082518145625-vCCEiiES', 'trace_id': '04fb6a8721abeee5b66edd452b4d0f33', 'base_resp': {'status_code': 0, 'status_msg': 'success'}}
257+
Generated audio saved as generated_audio.mp3
258+
```
259+
{% endcode %}
260+
261+
</details>
262+
263+
Listen to the track we generated:
264+
265+
{% embed url="https://drive.google.com/file/d/1sKlPIK6kiYrp6__VhKkgGpr65e8qy2PU/view?usp=sharing" %}

0 commit comments

Comments
 (0)