音频接口
录音的过程是通过调用微信js文件,获取js参数传送到php,实现跟wx服务器的交互。
该js接口会通过js方法调用微信里的录音控件,可以保存在本地,直接调用js方法进行播放,也可以将声音文件上传到wx服务器(保存三天),此期间可以从wx服务器将声音文件保存在自己服务器。
- 先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
- 在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.2.0.js
- wx.config({ }) //所有需要使用JS-SDK的页面必须先注入配置信息,否则将无法调用
如果是微擎的话,微擎会自动调用绑定的公众号的信息
$_W['account']['jssdkconfig'] = $account_api->getJssdkConfig()
在插件里面可以直接调用
var jssdkconfig = {php echo json_encode($_W['account']['jssdkconfig']);} || {};
wx.config(jssdkconfig);
- wx.ready(function(){}); //config信息验证后会执行ready方法
- wx.error(function(res){ }); // config信息验证失败会执行error函数
<img style="width: 2.5em;" src="{MODULE_URL}public/img/voice.png" onclick="voice.start();" alt=""/>
voice.start = function(e){
console.log(e);
if(recording){
voice.stop();
$('.fa-pause').addClass('fa-play').removeClass('fa-pause');
}
wx.ready(function(){
wx.startRecord({
cancel: function() {
$.toast("你拒绝了录音");
return ;
},
success: function() {
recording = true;
$('.fa-play').addClass('fa-pause').removeClass('fa-play');
timer = voice.timer();
}
});
wx.onVoiceRecordEnd({
complete: function(e) {
post.localId = e.localId;
recording = false;
$(e).find('.fa').removeClass('fa-pause');
$(e).find('.fa').addClass('fa-play');
$('.weui_dialog .weui_dialog_title').html('录制已达最大时间限制');
}
});
})
}
<button class="postVoice btn_voice" onclick="postVoice()" style="margin-top: 5px;font-size:1.2em;">
<i class="fa fa-paper-plane"></i>
发送
</button>
function postVoice(){
posting = true;
if(recording){
voice.stop(function(){
postTo();
});
}else{
postTo();
}
}
function postTo(){
post.desc = $('.weui_dialog .text_desc').val();
wx.ready(function(){
if(!post.localId){
$.toast("你说话了么?我怎么没听到!");
return '';
}
wx.uploadVoice({
localId: post.localId,
isShowProgressTips: 1,
success: function (res) {
alert(res.serverId);
post.serverId = res.serverId;
post.act = 'answer';
console.log(post);
if(!post.serverId){
$.toast("你说话了么?我怎么没听到!");
return '';
}
$.showLoading("正在发送数据");
$.post("",post,function(data){
if(data.status == 1){
$.hideLoading();
$.toast(data.message,2000,function(){
window.location.href = "{php echo $_W['siteurl']}";
});
}else{
$.toast(data.message,2000,'cancel');
$.hideLoading();
}
posting = false;
},'json');
}
});
});
}
voice.stop = function(callback){
wx.ready(function(){
wx.stopRecord({
success: function (res) {
post.localId = res.localId;
alert(res.localId);
recording = false;
if(callback){
callback();
}
setTimeout(function(){
$('.weui_dialog .weui_dialog_title').html('停止录音成功');
},1000);
}
});
});
}
php
if($act == 'answer'){
$serverId = trim($_GPC['serverId']);
$timelong = intval($_GPC['timelong']);
$data = array();
$data['uniacid'] = $_W['uniacid'];
$data['openid'] = $_W['openid'];
$data['voice_id'] = $serverId;
$data['isweixin'] = 0;
$data['timelong'] = $timelong;
$data['chart_id'] = $chart['id'];
$data['create_time'] = time();
$data['desc'] = trim($_GPC['desc']);
//df
$data['jf_time'] =date("Ymd") ;
$chart_log = M('chart_log')->update($data);
M('common')->createAudio('chart_log',$chart_log['id'],$serverId);
$data = array();
$data['status'] = 1;
$data['message'] = '发送成功';
$this->JFeveryDay(); //Delivery
die(json_encode($data));
}
class chart_log
{
public $table = 'imeepos_fvoice_chart_log';
public function __construct()
{
$this->install();
}
public function update($data){
global $_W;
$data['uniacid'] = $_W['uniacid'];
if(empty($data['id'])){
pdo_insert($this->table,$data);
$data['id'] = pdo_insertid();
}else{
//更新
pdo_update($this->table,$data,array('uniacid'=>$_W['uniacid'],'id'=>$data['id']));
}
return $data;
}
}
class common extends Imeepos_fvoiceModuleSite
{
public function createAudio($table,$id,$service_id=""){
global $_W;
$oauth_account = WeAccount::create($_W['account']['oauth']);
$token = $oauth_account->getAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$token."&media_id=".$service_id;
// echo $url;
$key = M('qiniu')->fetch($url,$service_id.".amr");
$re_url = $this->createMobileUrl('qiniu2mp3',array('id'=>$id,'table'=>$table));//创建网页地址
$re_url = str_replace('./','',$re_url);
$re_url = $_W['siteroot'].'app/'.$re_url;
M('qiniu')->toMp3($key,$re_url);
}
}
public function fetch($url,$key){
list($ret, $err) = $this->bucketMgr->fetch($url, $this->bucket, $key);
if ($err !== null) {
return false;
} else {
return $key;
return $ret;
}
}
public function toMp3($key,$return){
$data = 'bucket=' . $this->bucket . '&key=' . $key . '&fops=' . urlencode('avthumb/mp3') . '¬ifyURL=' . urlencode($return) . '&pipeline='.$this->mps;
$sign = hash_hmac('sha1', "/pfop/\n" . $data, $this->secret_key, true);
$token = $this->access_key . ':' . str_replace(array('+', '/'), array('-', '_'), base64_encode($sign));
$header = array('Content-Type:application/x-www-form-urlencoded', 'Authorization: QBox ' . $token);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.qiniu.com/pfop/');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = json_decode(curl_exec($curl), true);//访问网页并获得返回值
curl_close($curl);
$this->delete($key);
return $result;
}
public function delete($key){
$err = $this->bucketMgr->delete($this->bucket, $key);
if ($err !== null) {
return false;
} else {
return false;
}
}
voice.js
var voice = {};
var recording = false;
var localId = null;
var timer = null;
var post = {};
post.timelong = 0;
posting = false;
voice.show = function(){
console.log(_follow);
console.log(_openid);
if(_follow == 0 || _openid.length < 4){
$.modal({
title:'请扫码关注后发言',
text: '<img src="'+_qrcode+'" style="width:100%;"/>',
buttons: []
});
return '';
}
wx.ready(function(){
$.modal({
title:'语音录制',
text: $('#voicePanel').html(),
buttons: []
});
});
}
voice.play = function(){
if(!post.localId){
$.toast("你说话了么?我怎么没听到!");
return '';
}
wx.ready(function(){
wx.playVoice({
localId: post.localId,
success: function(e) {
// alert(post.localId);
playing = true;
},
error:function(){
$.toast("开启录音失败");
return '';
}
});
wx.onVoicePlayEnd({
complete: function(e) {
post.localId = res.localId;
playing = false;
$.toast("录音时间已达上限60秒");
return '';
}
});
});
}
voice.restart= function(){
post.timelong = 0;
recording = false;
voice.start();
}
voice.stop = function(callback){
wx.ready(function(){
wx.stopRecord({
success: function (res) {
post.localId = res.localId;
alert(res.localId);
recording = false;
if(callback){
callback();
}
setTimeout(function(){
$('.weui_dialog .weui_dialog_title').html('停止录音成功');
},1000);
}
});
});
}
voice.close = function(){
$('.weui_dialog').hide();
$('.weui_mask').removeClass('weui_mask_visible');
}
/*$(function(){
voice.timer();
})*/
voice.timer = function(){
return setTimeout(function(){
post.timelong = post.timelong + 1;
$('.weui_dialog .weui_dialog_title').html('录音中:'+post.timelong+'s');
if(recording){
timer = voice.timer();
}
},1000);
}
voice.start = function(e){
console.log(e);
if(recording){
voice.stop();
$('.fa-pause').addClass('fa-play').removeClass('fa-pause');
}
wx.ready(function(){
wx.startRecord({
cancel: function() {
$.toast("你拒绝了录音");
return ;
},
success: function() {
recording = true;
$('.fa-play').addClass('fa-pause').removeClass('fa-play');
timer = voice.timer();
}
});
wx.onVoiceRecordEnd({
complete: function(e) {
post.localId = e.localId;
recording = false;
$(e).find('.fa').removeClass('fa-pause');
$(e).find('.fa').addClass('fa-play');
$('.weui_dialog .weui_dialog_title').html('录制已达最大时间限制');
}
});
})
}
qn.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2016/7/2
* Time: 3:06
*/
require_once MODULE_ROOT.'/vendor/autoload.php';
use Qiniu\Config;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Qiniu\Processing\PersistentFop;
class qiniu {
public $auth;
public $bucketMgr;
public $bucket;
public $token;
public $uploadMgr;
public $policy;
public $pfop;
public $bucket_result;
public $mps;
public $access_key;
public $secret_key;
public function __construct()
{
$this->init();
}
public function init(){
global $_W;
$setting = M('setting')->getSetting('qiniu');
$access_key = $setting['access_key'];
$secret_key = $setting['secret_key'];
$this->mps = $setting['mps'];
$this->access_key = $access_key;
$this->secret_key = $secret_key;
$bucket = $setting['bucket_name'];
$bucket_result = $setting['bucket_name_result'];
$this->url = $setting['url'];
$this->bucket = $bucket;
$this->bucket_result = $bucket_result;
$this->auth = new Auth($access_key, $secret_key);
$this->bucketMgr = new BucketManager($this->auth);
$this->token = $this->auth->uploadToken($this->bucket);
$this->policy = array(
'callbackUrl' => $_W['siteroot'].'imeepos_print/qiniu.php',
'callbackBody' => 'filename=$(fname)&filesize=$(fsize)'
);
$this->uptoken = $this->auth->uploadToken($this->bucket, null, 3600, $this->policy);
$this->uploadMgr = new UploadManager();
}
public function check(){
return !empty($this->bucket)?true:false;
}
public function getUrl($key){
return $this->url."/".$key;
}
public function urlsafe_base64_encode($str){
$find = array("+","/");
$replace = array("-", "_");
return str_replace($find, $replace, base64_encode($str));
}
public function check_file($ext = ''){
$files = array('doc','docx','odt','rtf','wps','ppt','pptx','odp','dps','xls','xlsx','ods','csv','et');
foreach ($files as $f){
if($f == $ext){
return true;
}else{
return false;
}
}
}
public function toMp3($key,$return){
$data = 'bucket=' . $this->bucket . '&key=' . $key . '&fops=' . urlencode('avthumb/mp3') . '¬ifyURL=' . urlencode($return) . '&pipeline='.$this->mps;
$sign = hash_hmac('sha1', "/pfop/\n" . $data, $this->secret_key, true);
$token = $this->access_key . ':' . str_replace(array('+', '/'), array('-', '_'), base64_encode($sign));
$header = array('Content-Type:application/x-www-form-urlencoded', 'Authorization: QBox ' . $token);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.qiniu.com/pfop/');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
$this->delete($key);
return $result;
}
public function putFile($key, $filePath){
list($ret, $err) = $this->uploadMgr->putFile($this->token,$key, $filePath);
if ($err !== null) {
return $err;
} else {
return $ret;
}
}
public function fetch($url,$key){
list($ret, $err) = $this->bucketMgr->fetch($url, $this->bucket, $key);
if ($err !== null) {
return false;
} else {
return $key;
return $ret;
}
}
public function copy($key,$key2){
$err = $this->bucketMgr->copy($this->bucket, $key, $this->bucket, $key2);
if ($err !== null) {
return false;
} else {
return true;
}
}
public function delete($key){
$err = $this->bucketMgr->delete($this->bucket, $key);
if ($err !== null) {
return false;
} else {
return false;
}
}
public function stat($key=""){
list($ret, $err) = $this->bucketMgr->stat($this->bucket, $key);
if ($err !== null) {
return false;
} else {
return $ret;
}
}
public function move($key2,$key3){
$err = $this->bucketMgr->move($this->bucket, $key2, $this->bucket, $key3);
if ($err !== null) {
return false;
} else {
return true;
}
}
public function listFiles($marker,$limit){
$prefix = '';
list($iterms, $marker, $err) = $this->bucketMgr->listFiles($this->bucket, $prefix, $marker, $limit);
if ($err !== null) {
return false;
} else {
return array('iterms'=>$iterms,'marker'=>$marker);
}
}
}