-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstable_audio.js
98 lines (86 loc) · 3 KB
/
stable_audio.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const downloadFile = async (url, filePath) => {
try {
// Read the token from the token.json file
const tokenData = JSON.parse(fs.readFileSync(path.join(__dirname, 'token.json'), 'utf8'));
const token = tokenData.token;
let response;
let retryCount = 0;
const maxRetries = 50;
const retryDelay = 3000; // 3 seconds
while (retryCount < maxRetries) {
response = await axios({
url: url,
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br, zstd',
'Accept-Language': 'en-US,en;q=0.9'
},
responseType: 'stream'
});
if (response.status === 200) {
const writer = fs.createWriteStream(filePath);
response.data.pipe(writer);
await new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
console.log('File downloaded successfully!');
return;
} else if (response.status === 202) {
console.log('Generation in progress, retrying in 3 seconds...');
await new Promise(resolve => setTimeout(resolve, retryDelay));
retryCount++;
} else {
console.error('Error downloading file:', response.status);
return;
}
}
console.error('Maximum number of retries reached, unable to download file.');
} catch (error) {
console.error('Error downloading file:', error);
}
};
const generateAudio = async (prompt, lengthSeconds = 178, seed = 123) => {
try {
const tokenData = JSON.parse(fs.readFileSync(path.join(__dirname, 'token.json'), 'utf8'));
const token = tokenData.token;
const options = {
method: 'POST',
url: 'https://api.stableaudio.com/v1alpha/generations/stable-audio-audiosparx-v2-0/text-to-music',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
data: {
"data": {
"type": "generations",
"attributes": {
"prompts": [
{
"text": prompt,
"weight": 1
}
],
"length_seconds": lengthSeconds,
"seed": seed
}
}
}
};
const response = await axios(options);
console.log(`Status Code: ${response.status}`);
// Extract the result URL from the response
const resultUrl = response.data.data[0].links.result;
// Download the result file
const filePath = path.join(__dirname, 'audio_file.mp3');
await downloadFile(resultUrl, filePath);
} catch (error) {
console.error(`Error: ${error}`);
}
};
module.exports = { generateAudio };