微信的錄音文件上傳到微信服務器上,只能保存三天。 因此需要做一個轉存到自己服務器,或者七牛雲的操作。
轉存到自己服務器
- 調用微信JSSDK API 錄音, 錄音結束,上傳到微信服務器,獲取錄音文件的 media_id
- 根據 media_id 下載錄音文件(amr)格式
- 轉存到自己服務器(amr需要轉碼成mp3) 或者 七牛雲(有轉碼功能)
步驟1代碼
...
/**
* 開始錄音[省略了一部分代碼]
*/
startRecord: function() {
var that = this;
if (!that._startRecordFlag) {
typeof wx !== "undefined" && wx.startRecord({
success: function(res) {
Logger.log("res", res)
if (res.errMsg == 'startRecord:ok') {
Logger.log("正在開始錄音....")
that._startTime = new Date().getTime();
}
}
});
}
},
/**
* 結束錄音,並上傳
*/
stopRecord: function() {
that._startRecordFlag = false;
typeof wx !== "undefined" && wx.stopRecord({
success: function(res) {
//上傳錄音
wx.uploadVoice({
localId: res.localId,
isShowProgressTips: 1,
success: function(resUpload) {
//下載錄音文件到服務器,轉存起來
Model.downloadRecordAudio(resUpload.serverId, function(result) {
console.log(resUpload.serverId, result.path)
that.attachment = result.path;
// that.attachment = resUpload.serverId;
that.stopRecordCallback && that.stopRecordCallback();
})
}
});
}
});
},
...
步驟2代碼
<?php
//處理方法,
upload();
//media_id為微信jssdk接口上傳后返回的媒體id
function upload(){
$media_id = $_POST["media_id"];
$access_token = getAccessToken();
$path = "./weixinrecord/"; //保存路徑,相對當前文件的路徑
$outPath = "./php/weixinrecord/"; //輸出路徑,給show.php 文件用,上一級
if(!is_dir($path)){
mkdir($path);
}
//微 信上傳下載媒體文件
$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";
$filename = "wxupload_".time().rand(1111,9999).".amr";
downAndSaveFile($url,$path."/".$filename);
$data["path"] = $outPath.$filename;
$data["msg"] = "download record audio success!";
// $data["url"] = $url;
echo json_encode($data);
}
//獲取Token
function getAccessToken() {
// access_token 應該全局存儲與更新,以下代碼以寫入到文件中做示例
$data = json_decode(file_get_contents("./access_token.json"));
if ($data->expire_time < time()) {
$appid = "youappid"; //自己的appid
$appsecret = "youappsecret"; //自己的appsecret
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
$res = json_decode(httpGet($url));
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$fp = fopen("./access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
}
else {
$access_token = $data->access_token;
}
return $access_token;
}
//HTTP get 請求
function httpGet($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
//根據URL地址,下載文件
function downAndSaveFile($url,$savePath){
ob_start();
readfile($url);
$img = ob_get_contents();
ob_end_clean();
$size = strlen($img);
$fp = fopen($savePath, 'a');
fwrite($fp, $img);
fclose($fp);
}
?>
步驟3代碼【略】
目前沒有使用七牛雲,因此該部分代碼,參考七牛雲官網