背景
在社交应用,视频应用等领域,后端系统会收到用户上传的大量音视频文件,以及各种渠道商提供的音视频资料。这些数据的数据量大,频率高,质量参差不起,对系统的实时处理要求比较高,也给系统带来很大的压力。对于前端用户,也有自己不同的需求,比如流量不足的情况下,用户想选择清晰度没那么高的视频。对于后端系统,为了节省带宽,也会选择一定程度上的降低视频的清晰度。对于这种情况,我们可以使用云函数对这些视频文件处理,对应产生不同清晰度的视频,比如1080p,720p等,以满足不同场景下用户的需求,适应用户宽带小,流量少,网络不稳定的情况。
方案设计
整体数据流转如图所示:
详细步骤:
1.在云函数控制台创建云函数,代码如下:
/************************************************************************* ***** ***** ***** 使用教程/readme : ***** ***** https://cloud.tencent.com/document/product/583/47071 ***** ***** ***** **************************************************************************/ const COS = require('cos-nodejs-sdk-v5'); const fs = require('fs') const child_process = require('child_process') const util = require('util'); exports.main_handler = async (event, context) => { try { let downloadPath = '' let key = '' if (event.hasOwnProperty('body')) { downloadPath = event.body key = downloadPath.split('/').pop() } else if (event.hasOwnProperty('Records')) { key = event['Records'][0]['cos']['cosObject']['key'].split("/").pop() downloadPath = event['Records'][0]['cos']['cosObject']['url'] } else { return {"code": 410, "errorMsg": "event does not come from COS or APIGW"} } key = `new-${key}` const uploadPath = `/tmp/${key}` const region = process.env.region const targetBucket = process.env['target_bucket'] const targetPath = process.env['target_path'] || '' const secretId = process.env['TENCENTCLOUD_SECRETID'] const secretKey = process.env['TENCENTCLOUD_SECRETKEY'] const token = process.env['TENCENTCLOUD_SESSIONTOKEN'] const cos = new COS({ SecretId: secretId, SecretKey: secretKey, XCosSecurityToken: token }) child_process.execSync('cp ./ffmpeg /tmp/ffmpeg') child_process.execSync('chmod 755 /tmp/ffmpeg') child_process.execSync(`./ffmpeg -i ${downloadPath} -r 10 -b:a 32k ${uploadPath}`, { cwd: "/tmp" }) const putObjectAync = util.promisify(cos.putObject.bind(cos)) await putObjectAync({ Bucket: targetBucket, Region: region, Key: `${targetPath}/${key}`, Body: fs.readFileSync(uploadPath) }) fs.unlinkSync(uploadPath) return 'success' } catch (err) { console.log(err) return 'failed' } } |
---|
2.创建COS触发器。上传音视频文件后立刻触发云函数的处理逻辑。
3.配置挂在CFS,由于音视频文件一般较大,所以需要挂在额外的文件系统。