前端在微信中利用微信公众号实现录音

1,186 阅读3分钟

因为工作需求,需要实现一个类似微信语音录音功能。

开始我想了一下浏览器Window下不是有一个MediaRecorder API,可以进行录音的功能,我很高兴就封装了一个录音的组件,自我测试了一下发现浏览器没什么问题,心想拿捏了简简单单。等我在微信内访问我的H5的时候发现报错,我一打印发现微信里找不到MediaRecorder,查阅资料发现微信内有提供方法,但是要基于公众号,由于官方给的文档比较杂乱隐秘不好找到,我这里精简一下

基于JSSDK使用

步骤一:绑定域名

先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。

备注:登录后可在“开发者中心”查看对应的接口权限。

步骤二:引入JS文件

在需要调用JS接口的页面引入如下JS文件,(支持https):res.wx.qq.com/open/js/jwe…

由于我是基于Umi开发,我在Config中做好了相应的配置

import { defineConfig } from 'umi';
export default defineConfig({
  ......
  headScripts: ['https://res.wx.qq.com/open/js/jweixin-1.6.0.js'],
 ......
});

步骤三:在页面中使用

1.初始化
const audioInit = async () => {
    const res = await getTicket(window.location.href); 
    //用户获取一些信息,可以从后端获取
    // 配置微信 jssdk
    if (!res) return;
    window.wx.config({
      debug: false,//如果是ture就会打开debug模式,每次调试会自动弹框信息
      appId: res.appId, // 必填,公众号的唯一标识
      timestamp: res.timestamp, // 必填,生成签名的时间戳
      nonceStr: res.nonceStr, // 必填,生成签名的随机串
      signature: res.signature, // 必填,签名
      jsApiList: ['checkJsApi', 'startRecord', 'stopRecord', 'uploadVoice'], // 必填,需要使用的 JS 接口列表,这里为我只用了检查JSApi,录音,停止录音,以及上传录音
    });
  };
2.页面中按钮调用函数,我自己仿微信写了这一个页面

IMG_877DC5875227-1.jpeg

    ......

         <Button
            onClick={handleStartRecording}
            color="primary"
            fill="none"
          >
            <span className={styles.btn}>按下 说话</span>
          </Button>
          <Button
            onClick={handleStopRecording}
            color="primary"
            fill="none"
          >
            <span className={styles.btn}>结束 说话</span>
          </Button>
    ......
3.开始录音

 const handleStartRecording = () => {
 //调用微信开始录音方法
    window.wx.startRecord({
      success: () => {
        console.log('开始录音...');
      },
      fail: (err: any) => {
        console.error('录音失败:', err);
        setPressing(false);
      },
    });
  };
4.停止录音
 //调用微信停止录音方法
     const handleStopRecording = () => {
        window.wx.stopRecord({
          success: (res: any) => {
            const localId = res.localId;
            updateAudio(localId); //上传语音,需要上传的音频的本地ID
          },
          fail: (err: any) => {
            console.error('停止录音失败:', err);
          },
        });
      };
5.获取音频
window.wx.uploadVoice({
  localId, // 需要上传的音频的本地ID,由stopRecord接口获得
  isShowProgressTips: 1, // 默认为1,显示进度提示
  success: function (res: any) {
    const serverId = res.serverId; // 返回音频的服务器端ID
    //后续可以上传到自己的服务器,使用
    ....
  },
});

最后我们可以使用ReactPlayer组件在页面中播放,这里不详细讲解如果想实现控制每一个音频,类型播放下一个,上一个中断

 const players = useRef([]);
const [player, setPlayer] = useState(undefined);
......
 function handleProgress(val: OnProgressProps) {
    console.log(val, 'val');
    if (val?.played == 1) {
      setPlayer(undefined);
    }
  }
......
//由于有多个音频我这个是遍历出来的
<ReactPlayer
    ref={(player) => (players.current[index] = player)}
    width="100%"
    height="100%"
    url={item.msg}
    playing={player == index}
    loop={false}
    onProgress={(val) => handleProgress(val)}
/>


//如果想重置需要在点击当前的时候,把其他音频重置,这里提供单一重置的方法

  const resetPlayer = (index: any) => {
    let player: any = {};
    players.current.map((v: any, i: any) => {
      if (i === index) {
        player = v;
      }
    });
    if (player && player.getInternalPlayer()) {
      player.seekTo(0);//用户把语音进度重置为0
    }
  };

以上就是仿照微信利用微信公众号实现录音的大致步骤