Home  >  Article  >  WeChat Applet  >  Recording function developed by WeChat

Recording function developed by WeChat

Y2J
Y2JOriginal
2017-05-09 10:04:572950browse

WeChat jssdk recording function development record

Tags (space separated): Front-end


0. Requirement description

The page opened in the WeChat browser, Make a button that starts recording when the user presses it, stops recording when they release it, and uploads the recording for long-term storage.


1. Development process

If you develop an ordinary display page, it is no different from developing an ordinary page, but you need to use a device (mobile phone) here To use the recording function, you need to call the recording interface of the WeChat app and use the 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" Fill in the "JS interface security domain name". [WeChat public account required]

  • Introduce JS files

  • Inject permission verification configuration through the config interface

  • Processing successful verification through the ready interface

  • Processing 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可以在这里更新签名。

});
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: &#39;后端处理上传录音的接口&#39;,
                type: &#39;post&#39;,
                data: JSON.stringify(res),
                dataType: "json",
                success: function (data) {
                    alert(&#39;文件已经保存到七牛的服务器&#39;);//这回,我使用七牛存储
                },
                error: function (xhr, errorType, error) {
                    console.log(error);
                }
            });
        }
    });
}

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


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 playback recording interface event

Callback functionInvalid

WeChat registration events must be placed in wx.ready.

Prevent the default event

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

WeChat storage

staticThe resource time is 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 Waiting for the format!
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 recording is used for the first time, WeChat will pop up a dialog box asking whether 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 record 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 on it instead. Allow, recording will actually start after the user gives permission. 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 !== &#39;true&#39;){
    wx.startRecord({
        success: function(){
            localStorage.rainAllowRecord = &#39;true&#39;;
            wx.stopRecord();
        },
        cancel: function () {
            alert(&#39;用户拒绝授权录音&#39;);
        }
    });
}

3. Problem

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

However, the volume of the 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).

This issue is being communicated to relevant WeChat technical personnel.

The temporary solution is: for the audio just recorded, use wx.playVoice to play it, otherwise use audio to play the server resource. The reason is that it is not sure whether the audio exists locally. The audio just recorded definitely exists.

【Related recommendations】

1.

WeChat public account platform source code download

2.

Alizi order system source code free download

The above is the detailed content of Recording function developed by WeChat. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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