目次
必要
クラウド研修システムでは、ビデオコースウェアの制作が主な業務の一つですが、制作完了後、その教材をサーバーに保存し、再生できるように配布するのは目の前の問題です。最終的に、Tencent Cloud オンデマンド サービスを選択しました。その高速配信と再生は、画像、オーディオ、ビデオ メディア コンテンツを表示する必要があるほぼすべてのオンライン シナリオに適しています。周囲の多数の CDN 高速化ノードの助けを借りて、複雑なネットワーク環境でも高品質のメディア コンテンツを提供でき、サービスにアクセスできます。
ビデオアップロード機能は主に次の 2 つの問題を解決します。
1. サーバー側で C# を使用して署名と SDKID を生成する
2. クライアント上の JavaScript を通じて、ビデオを Tencent Cloud オンデマンド サーバーにアップロードします。
キーコード
インターフェース要素のレイアウト
ファイル アップロード コントロール (id: file1)、アップロード進行状況バーの灰色の背景レイヤー (id: ajax_uploadFiles_curbg)、アップロード進行状況バーの進行状況画像 (id: ajax_uploadFiles_curprogress)、およびプロンプト テキスト レイヤー ( id:tip )、画像とレイヤーは絶対的に配置され、アップロードプロセス中に進行状況の値が計算されて、進行状況画像の幅が決定されます。
サンプルコードは次のとおりです。
<div>
<input type="file" accept=".mp4,.mp3" id="file1" onchange="vUpload()" />
<img id="ajax_uploadFiles_curprogress" style="z-index:1;position:absolute;left:0px;top:4px;width:0px;height:12px" alt="" src="win7progress.jpg" />
<div id="ajax_uploadFiles_curbg" style="display:none;z-index:0;position:absolute;left:0px;top:4px;width:203px;height:12px;background-color:Gray"></div>
<div id="tip" style="z-index:0;position:absolute; font-size:9pt;left:205px;top:2px;height:12px;"></div>
</div>
C# はサーバー側の署名クラスを実装します。
アップロードする前に、開発 APPID と開発キーを指定して有効な署名を生成してからアップロードする必要があります。サンプル コードは次のとおりです。
public class Signature
{
public string m_strSecId;
public string m_strSecKey;
public int m_iRandom;
public long m_qwNowTime;
public int m_iSignValidDuration;
public static long GetIntTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1);
return Convert.ToInt64(ts.TotalSeconds);
}
private byte[] hash_hmac_byte(string signatureString, string secretKey)
{
var enc = Encoding.UTF8; HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
hmac.Initialize();
byte[] buffer = enc.GetBytes(signatureString);
return hmac.ComputeHash(buffer);
}
public string GetUploadSignature()
{
string strContent = "";
strContent += ("secretId=" + Uri.EscapeDataString((m_strSecId)));
strContent += ("¤tTimeStamp=" + m_qwNowTime);
strContent += ("&expireTime=" + (m_qwNowTime + m_iSignValidDuration));
strContent += ("&random=" + m_iRandom);
byte[] bytesSign = hash_hmac_byte(strContent, m_strSecKey);
byte[] byteContent = System.Text.Encoding.Default.GetBytes(strContent);
byte[] nCon = new byte[bytesSign.Length + byteContent.Length];
bytesSign.CopyTo(nCon, 0);
byteContent.CopyTo(nCon, bytesSign.Length);
return Convert.ToBase64String(nCon);
}
public string getSign(int SignValidSeconds){
Signature sign = new Signature();
sign.m_strSecId = secretId; //开发ID
sign.m_strSecKey = secretKey; //开发密钥
sign.m_qwNowTime = Signature.GetIntTimeStamp();
sign.m_iRandom = new Random().Next(0, 1000000);
sign.m_iSignValidDuration = SignValidSeconds;
return rv = "{\"errcode\":0,\"sign\":\"" + sign.GetUploadSignature() + "\",\"sdkid\":\"1111111111\"}";
}
}
Signature クラスの getSign(int SignValidSeconds) メソッドを呼び出して署名を生成します。パラメータは署名が有効な秒数です。
動画アップロードのJS実装
関数を実装する前に、必要な JS ファイルを参照する必要があります。リソースのダウンロード リンクのアドレス:https://download.csdn.net/download/michaelline/88555774
//引用必要的三个js
<script src="jquery-3.2.1.min.js"></script>
<script src="es6-promise.auto.js"></script>
<script src="vod-js-sdk-v6.js"></script>
<script type="text/javascript">
var sign = "";
var sdkid="";
var tcVod = null;
var timer=null;
var ws=0;
var fileobj=document.getElementById('file1');
var curbg=document.getElementById('ajax_uploadFiles_curbg');
var progressBarWidth=parseInt(curbg.style.width,10);
//重新或尝试获取sign
function resign() {
return sign;
}
//与服务器API地址交互获得签名值和SDKID,有效时间为3600秒
function getsign() {
$.ajax({
type: "Post",
url: '<%=ViewState["apiurl"].ToString()%>',
contentType: "application/x-www-form-urlencoded;charset=utf-8",
data: {
validSeconds: 3600
},
dataType: "json",
success: function (res) {
//返回的数据用data.d获取内容
if (res.errcode == 0) {
sign = res.sign;
sdkid=res.sdkid;
initTcVod();
} else {
alert('上传暂时无法使用。');
}
},
error: function (err) {
alert(err);
}
});
}
getsign(); //获取一次签名值
function timetip(off) {
var z = parseInt(off / 60, 10);
var y = off % 60;
var mtip='';
var stip='';
if(z==0&&y!=0){
stip=y+'秒';
} else if (z != 0 && y == 0) {
mtip = z +'分钟';
} else if (z != 0 && y != 0) {
mtip = z + '分';
stip = y + '秒';
}
return mtip+stip;
}
//初始化腾讯上传组件
function initTcVod() {
tcVod = new TcVod.default({getSignature: resign});
}
//上传视频
function vUpload(){
ws=0;
curbg.style.display='';
timer=window.setInterval(function(){ws++},1000);
var mediaFile = document.getElementById('file1').files[0];
var uploader = tcVod.upload({
mediaFile: mediaFile,mediaName:sdkid+mediaFile.name,
});
uploader.on('media_progress', function (info) {
fileobj.style.display='none';
document.getElementById('tip').innerHTML='已上传'+ Math.round(info.percent*100)+'%(耗时'+timetip(ws)+')';
document.getElementById('ajax_uploadFiles_curprogress').style.width=(progressBarWidth*info.percent)+'px';
})
uploader.on('media_upload', function (info) {
window.clearInterval(timer);
document.getElementById('tip').innerHTML='上传成功!';
执行后续操作...
}else{
}
})
}
</script>
ビデオデモンストレーション
JS はオンデマンドで Tencent Cloud にビデオをアップロードします
まとめ
上記のコードは参考用です。実際のアプリケーションでは、サーバー側 API URL プログラムには認証やインスタント トークン アクセスなどのセキュリティ メカニズムも必要です。
さらに、Tencent Cloud Media Upload では、複数のアップロード方法用の SDK も提供しています。詳細については、Web サイトを参照してください。https://cloud.tencent.com/document/製品/266/ 9760
上記は私のシェアの一部です。時間が限られているので、不正確な点があれば批判して修正してください。