小程序内嵌webview使用audio播放音频

private setAudio(): void {
  const addAd = () => {
      let ad = document.createElement('audio');
      ad.setAttribute('autoplay', true);
      ad.src = `https://houtaicdn.alva.com.cn/medias/resources/wechat/meishuguan/audio/hello.mp3`;
      let t = setTimeout(() => {
          clearTimeout(t);
          ad.src = `resources/ad/renwu.mp3`;
          ad.play();
      }, 5000);
      document.body.appendChild(ad);
  }

  const addAdCtx = () => {
      var ctx = new (window.AudioContext || window.webkitAudioContext())();
      let source = ctx.createBufferSource(); // 创建音频源头姐点

      // 播放
      async function playAudio() {
          const audioBuffer = await loadAudio("resources/ad/renwu.mp3");
          playSound(audioBuffer);
      }
      // 暂停
      async function resumeAudio() {
          if (ctx.state === "running") {
              ctx.suspend();
          } else if (ctx.state === "suspended") {
              ctx.resume();
          }
      }
      // 停止
      async function stopAudio() {
          source.stop();
      }
      async function loadAudio(audioUrl) {
          const res = await fetch(audioUrl);
          const arrayBuffer = await res.arrayBuffer(); // byte array字节数组
          const audioBuffer = await ctx.decodeAudioData(arrayBuffer, function(decodeData) {
              return decodeData;
          });
          return audioBuffer;
      }
      async function playSound(audioBuffer) {
          source.buffer = audioBuffer; // 设置数据
          source.loop = true; //设置,循环播放
          source.connect(ctx.destination); // 头尾相连
          // 可以对音频做任何控制
          source.start(0); //立即播放
      }
      playAudio();
  }

  this.browerType((res) => {
      if (res === 2) { // 微信环境
        if (this.isIOS()) {
          addAd();
        } else {
          setTimeout(() => {
              addAdCtx();
          }, 20)
        }
      } else {
          addAd();
      }
    })
}
private browerType(resfun) {
  var ua = window.navigator.userAgent.toLowerCase()
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      let self = this;
    // 微信环境下
    wx.miniProgram.getEnv(function(res) {
      if (res.miniprogram) {
        // 小程序环境下逻辑
        resfun(2);
      } else {
        // 非小程序环境下逻辑
        resfun(1);
      }
    })
  } else {
    resfun(0);
  }
}
private isIOS() {
  var isIphone = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  return isIphone
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值