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
}
小程序内嵌webview使用audio播放音频
最新推荐文章于 2024-05-22 15:35:29 发布