AWS Lambda 在默认情况下只能执行 300 秒的运行时间,因此在 FFMPEG 转换完 5 秒视频之后,Lambda 函数将会超时并停止运行。解决这个问题的方法是将视频文件分成多个 5 秒的片段并单独转换,然后合并成一个视频文件。
下面是一个基于 Node.js 的示例代码:
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const ffmpeg = require('fluent-ffmpeg');
exports.handler = async (event, context, callback) => {
const inputKey = event.inputKey;
const outputKey = event.outputKey;
// 下载原始视频文件
const inputParams = {
Bucket: event.inputBucket,
Key: inputKey
};
const inputFile = await s3.getObject(inputParams).promise();
// 将视频拆分为 5 秒的片段并转码
const ffmpegCmd = ffmpeg(inputFile.Body)
.outputOptions([`-f segment`, `-segment_time 5`])
.videoCodec('libx264')
.noAudio()
.on('end', async () => {
// 将所有片段合并为一个视频文件
const mergeCmd = ffmpeg();
for(let i = 0; i < segmentCount; i++) {
mergeCmd.addInput(`segment-${i}.mp4`);
}
mergeCmd.outputOptions(`-f mp4`).on('end', async () => {
// 将转换后的视频上传到 S3
const outputParams = {
Bucket: event.outputBucket,
Key: outputKey,
Body: outputFile
};
await s3.upload(outputParams).promise();
callback(null, 'Video conversion complete');
}).mergeToFile(outputKey);
});
ffmpegCmd.run();
};
这个 Lambda 函数会从输入 S3 存储桶中下载视频文件,然后使用 FFMPEG 进行转换,并将转换后的视频文件上传到指定
上一篇:AWSLambda中使用eval()和列表推导结合会出现问题。
下一篇:AWSLambda中使用Jersey时出现Missingauthorizationtoken的错误设置不涉及APIGateway