const fs = require('fs');
const https = require('https');
class Veo3Client {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.kie.ai';
this.headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
};
}
// 生成视频
async generateVideo(prompt, options = {}) {
const payload = {
prompt,
model: options.model || 'veo3',
aspectRatio: options.aspectRatio || '16:9',
...options
};
try {
const response = await fetch(`${this.baseUrl}/api/v1/veo/generate`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify(payload)
});
const data = await response.json();
if (response.ok && data.code === 200) {
return data.data.taskId;
} else {
throw new Error(`生成视频失败: ${data.msg || '未知错误'}`);
}
} catch (error) {
throw new Error(`生成视频失败: ${error.message}`);
}
}
// 查询状态
async getStatus(taskId) {
try {
const response = await fetch(`${this.baseUrl}/api/v1/veo/record-info?taskId=${taskId}`, {
method: 'GET',
headers: { 'Authorization': this.headers.Authorization }
});
const data = await response.json();
if (response.ok && data.code === 200) {
return data.data;
} else {
throw new Error(`查询状态失败: ${data.msg || '未知错误'}`);
}
} catch (error) {
throw new Error(`查询状态失败: ${error.message}`);
}
}
// 等待完成
async waitForCompletion(taskId, maxWaitTime = 600000) { // 默认最多等待10分钟
const startTime = Date.now();
while (Date.now() - startTime < maxWaitTime) {
const status = await this.getStatus(taskId);
console.log(`任务 ${taskId} 状态: ${status.successFlag}`);
if (status.successFlag === 1) {
return status.response.resultUrls;
} else if (status.successFlag === 2 || status.successFlag === 3) {
throw new Error('视频生成失败');
}
await new Promise(resolve => setTimeout(resolve, 30000)); // 等待30秒
}
throw new Error('任务超时');
}
// 下载视频
async downloadVideo(url, filename) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(filename);
https.get(url, (response) => {
if (response.statusCode === 200) {
response.pipe(file);
file.on('finish', () => {
file.close();
console.log(`视频已下载: ${filename}`);
resolve(filename);
});
} else {
reject(new Error(`下载失败: HTTP ${response.statusCode}`));
}
}).on('error', reject);
});
}
// 完整流程
async generateAndDownload(prompt, filename = 'video.mp4', options = {}) {
try {
console.log('开始生成视频...');
const taskId = await this.generateVideo(prompt, options);
console.log(`任务已提交: ${taskId}`);
console.log('等待生成完成...');
const videoUrls = await this.waitForCompletion(taskId);
console.log('视频生成完成!');
console.log('开始下载视频...');
await this.downloadVideo(videoUrls[0], filename);
return { taskId, videoUrls, filename };
} catch (error) {
console.error('错误:', error.message);
throw error;
}
}
}
// 使用示例
async function main() {
const client = new Veo3Client('YOUR_API_KEY');
try {
const result = await client.generateAndDownload(
'一只可爱的小猫在花园里玩耍,阳光明媚,高清画质',
'cute_cat.mp4',
{ aspectRatio: '16:9' }
);
console.log('完成!', result);
} catch (error) {
console.error('生成失败:', error.message);
}
}
main();