写得不错:http://www.cnblogs.com/zhongxia/p/5917163.html
微信的录音文件上传到微信服务器上,只能保存三天。 因此需要做一个转存到自己服务器,或者七牛云的操作。
转存到自己服务器
调用微信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.
stopRecordCallback && that.
stopRecordCallback()
;
})
}
})
;
}
})
;
},
...
步骤2代码
<?php
upload
();
function upload(){
$media_id =
$_POST["media_id"];
$access_token = getAccessToken
();
$path =
"./weixinrecord/";
$outPath =
"./php/weixinrecord/";
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!";
echo json_encode($data);
}
function getAccessToken() {
$data =
json_decode(file_get_contents("./access_token.json"));
if ($data->expire_time <
time()) {
$appid =
"youappid";
$appsecret =
"youappsecret";
$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;
}
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;
}
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);
}
?>
转载请注明原文地址: https://ju.6miu.com/read-677799.html