Home > WeChat Applet > WeChat Development > WeChat jssdk recording function development record

WeChat jssdk recording function development record

高洛峰
Release: 2017-02-15 11:30:58
Original
2782 people have browsed it

WeChat jssdk recording function development record

0. Requirement description

Create a button on the page opened in the WeChat browser. The user starts recording after pressing and holding the button, and stops recording after letting go. And upload the recording and save it for a long time.

1. Development process

If you are developing an ordinary display page, it is no different from developing an ordinary page. However, the recording function of the device (mobile phone) needs to be used here. To call the recording interface of WeChat app, you need to use WeChat jssdk.

Use WeChat jssdk: WeChat JS-SDK documentation

  • First log in to the WeChat public platform and enter the "Function Settings" of "Official Account Settings" to fill in " JS interface security domain name". [WeChat public account required]

  • Introduce JS files

  • Inject permission verification configuration through the config interface

  • Process successful verification through the ready interface

  • Process failed verification through the error interface

##
//假设已引入微信jssdk。【支持使用 AMD/CMD 标准模块加载方法加载】
wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '', // 必填,公众号的唯一标识
    timestamp: , // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '',// 必填,签名,见附录1
    jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});

wx.ready(function(){

    // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
});

wx.error(function(res){

    // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。

});
Copy after login
The core function of this requirement: recording And save

//假设全局变量已经在外部定义
//按下开始录音
$('#talk_btn').on('touchstart', function(event){
    event.preventDefault();
    START = new Date().getTime();

    recordTimer = setTimeout(function(){
        wx.startRecord({
            success: function(){
                localStorage.rainAllowRecord = 'true';
            },
            cancel: function () {
                alert('用户拒绝授权录音');
            }
        });
    },300);
});
//松手结束录音
$('#talk_btn').on('touchend', function(event){
    event.preventDefault();
    END = new Date().getTime();
    
    if((END - START) < 300){
        END = 0;
        START = 0;
        //小于300ms,不录音
        clearTimeout(recordTimer);
    }else{
        wx.stopRecord({
          success: function (res) {
            voice.localId = res.localId;
            uploadVoice();
          },
          fail: function (res) {
            alert(JSON.stringify(res));
          }
        });
    }
});

//上传录音
function uploadVoice(){
    //调用微信的上传录音接口把本地录音先上传到微信的服务器
    //不过,微信只保留3天,而我们需要长期保存,我们需要把资源从微信服务器下载到自己的服务器
    wx.uploadVoice({
        localId: voice.localId, // 需要上传的音频的本地ID,由stopRecord接口获得
        isShowProgressTips: 1, // 默认为1,显示进度提示
        success: function (res) {
            //把录音在微信服务器上的id(res.serverId)发送到自己的服务器供下载。
            $.ajax({
                url: '后端处理上传录音的接口',
                type: 'post',
                data: JSON.stringify(res),
                dataType: "json",
                success: function (data) {
                    alert('文件已经保存到七牛的服务器');//这回,我使用七牛存储
                },
                error: function (xhr, errorType, error) {
                    console.log(error);
                }
            });
        }
    });
}

//注册微信播放录音结束事件【一定要放在wx.ready函数内】
wx.onVoicePlayEnd({
    success: function (res) {
        stopWave();
    }
});
Copy after login


2. Little trouble

To prevent invalid recording caused by user misoperation (such as repeated clicks, accidental touches).

No recording when less than 300ms

Prevent the WeChat browser’s default “copy dialog box” from popping up by the browser caused by the user’s long press.

Use css to set the button user-select:none;

WeChat play recording interface event callback function is invalid

WeChat registration event must be Put it in wx.ready.

Prevent default events

Touch events remember to add event.preventDefault(); Fire and explosion protection

WeChat stores static resources for 3 days , how to save it for a long time

Either save it to your own server, or use other resources, such as Qiniu, which can also help us freely convert amr format to mp3 and other formats!

The default resource format of WeChat server is amr. This format can be played using the audio tag on android machines, but cannot be played on ios machines using the audio tag.

Interaction issues caused by authorization of WeChat recording function

Using WeChat jssdk interface to record, you only need to authorize it once in the same domain, that is, when you use recording for the first time. WeChat itself will pop up a dialog box asking if recording is allowed. After the user clicks Allow, the user will not be asked for permission when recording is used again.

After pressing and holding the recording button for the first time, since the user has not allowed recording, WeChat will prompt the user to authorize the use of the WeChat recording function on this page. At this time, the user will release the recording button and click Allow. After the user allows it, , the recording will actually start. At this time, the user has already released the recording button, so there will be no touchend event on the recording button, and the recording will continue.
Solution strategy: Use localStorage to record whether the user has authorized it, and use this to determine whether it is necessary to automatically record a recording when just entering the page to trigger user authorization

if(!localStorage.rainAllowRecord || localStorage.rainAllowRecord !== 'true'){
    wx.startRecord({
        success: function(){
            localStorage.rainAllowRecord = 'true';
            wx.stopRecord();
        },
        cancel: function () {
            alert('用户拒绝授权录音');
        }
    });
}
Copy after login

3. Problem

Volume bug: On an ios device, after using the WeChat recording function and then playing the audio tag, the volume is extremely low.

However, the volume of recording played using the WeChat interface (wx.playVoice) is normal, and after that, the volume of the audio tag will increase (but the volume will still be very low).

For more articles related to WeChat jssdk recording function development records, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template