const axios = require('axios');
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 axios.post(`${this.baseUrl}/api/v1/veo/generate`, payload, {
headers: this.headers
});
return response.data.data.taskId;
} catch (error) {
throw new Error(`生成视频失败: ${error.response?.data?.msg || error.message}`);
}
}
// 查询状态
async getStatus(taskId) {
try {
const response = await axios.get(`${this.baseUrl}/api/v1/veo/record-info?taskId=${taskId}`, {
headers: this.headers
});
return response.data.data;
} catch (error) {
throw new Error(`查询状态失败: ${error.response?.data?.msg || 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.status}`);
if (status.status === 1) {
return JSON.parse(status.resultUrls);
} else if (status.status === 2 || status.status === 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();