$serverId = $_POST['serverId'];//传过来的serverID,也就是media_id
$path = "./sound/"; //保存路径
$outPath = "./record/"; //输出路径
$access_token = getAccessToken();
if(!is_dir($path)){
mkdir($path);
}
//https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_temporary_materials.html
//高清语音素材获取接口
//$url = "https://api.weixin.qq.com/cgi-bin/media/get/jssdk?access_token={$access_token}&media_id={$serverId}";
//普通素材获取
$url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$serverId}";
$file_amr = $openid.time().".amr";
$file_mp3 = $openid.time().".mp3";
$amr = $outPath.$file_amr;
$mp3 = $path.$file_mp3;
downAndSaveFile($url,$outPath.$file_amr);
$duration = 0;
$state='';
if(file_exists($amr))
{
// echo "当前目录中,文件".$amr."存在";
$command = "/usr/local/ffmpeg_sources/FFmpeg/ffmpeg -i $amr $mp3";
exec($command,$out,$state);
if($state == 0){
echo "转换成功";
}else{
echo "转换失败";
}
}
//获取Token
function getAccessToken() {
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("./access_token.json"));
if ($data->expire_time < time()) {
$appid = "xxxxxxxxxxx"; //你自己的appid
$appsecret = "xxxxxxxxxx"; //你自己的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();
$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);
}