0
点赞
收藏
分享

微信扫一扫

uni-app 实现自定义音效播放

Gaaidou 2022-01-27 阅读 179

背景

第一步 下载需要的音效

在 aigei 这个网站上搜索需要的音效,免费的。根据自己的需求来选,比如我需要的是一个点击音效,那这个音效肯定不能太长,不得大于一秒钟。

下载好之后,要把这个音效放到公网上,可以放到自己的服务器上,我这里就放到了阿里云的OSS上

第二步 在uni-app中使用

使用uni-appcreateinneraudiocontext”api。
uni-app 的文件目录如下:

//utils.js

//因为这个音效听起来是叮的声音,所以我取这个函数名,方便记忆音效,找的合适的场景就能想起来。
function play_ding() {
	wx.setInnerAudioOption({
		obeyMuteSwitch: false, //(仅在 iOS 生效)是否遵循静音开关,设置为 false 之后,即使是在静音模式下,也能播放声音
		fail: function(e) {
			debug.log('e', e)
		}
	});
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	innerAudioContext.src = 'https://xxx/ding.mp3';
	innerAudioContext.onPlay(() => {
	});
	innerAudioContext.onError((res) => {
	});
	setTimeout(() => {
		innerAudioContext.destroy() // 音效一般为1s,2s后销毁实例
	}, 2000)
}

module.exports = {
	play_ding,
}

在需要使用的某一个页面或组件中

import util from "utils/util.js"
methods: {
  finished() {
    util.play_ding()
  },
}
举报

相关推荐

0 条评论