注意
uniapp API 中 uni.createInnerAudioContext()是无法多音频播放的 如果我们想同时播放 加上ambient(不中止其他声音播放,不能后台播放,静音后无声音)这个属性,我做的这个是用uniapp开发的一个安卓端的壳包,正常h5用MP3,WMA或者MPEG等格式的音频都是可以的,但在安卓端手机测试需要使用MP3格式的音频,否则会没有声音。
效果图
主要代码
首先全局定义播放器
// 定义全局播放器
var musicSelect = null;
musicSelect = uni.createInnerAudioContext(); //创建时间选择播放器对象 选择时间播放机械声
/*
"ambient" - 不中止其他声音播放,不能后台播放,静音后无声音;
"soloAmbient" - 中止其他声音播放,不能后台播放,静音后无声音;
"playback" - 中止其他声音,可以后台播放,静音后有声音。
*/
musicSelect.sessionCategory = "ambient"
musicSelect.src = "https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/trim.mp3";
var music = null;
music = uni.createInnerAudioContext(); //创建雨林鸟播放器对象
// music.sessionCategory = "ambient"
music.src = "https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/yu-music.mp3";
这是我随便写的样式 点击对应文字切换文章来源:https://www.toymoban.com/news/detail-505801.html
<!-- 雨 林 鸟 播放音乐 -->
<view class="music" v-if="windowSteep>0&&isShowMusic">
<view class="music-flex" v-for="(item, index) in musicList" :key="index" @click="musicClick(item, index)">
<image class="music-img" :src="getMusic(item)" mode="widthFix"></image>
<view class="yuanq" :class="{'yuanq-red': item.isPlay}"></view>
</view>
</view>
这是methods中的点击事件 点击播放和暂停文章来源地址https://www.toymoban.com/news/detail-505801.html
// 点击雨林鸟播放或者暂停音乐
musicClick(item,index) {
// isPlay控制是否选中的状态
this.musicList.filter(e => {
if(e.id !== item.id) {
e.isPlay = false
} else {
e.isPlay = !e.isPlay
}
})
music.src = item.music;
// 如果isPaly为true则播放当前音乐 暂停其他音乐
if(item.isPlay) {
// 播放
music.play()
music.onEnded(() => {
//播放结束 循环播放
music.play()
});
} else {
// 暂停
music.pause()
}
},
放上所有的代码
<template>
<view class="pages" @click="windowClick">
<view v-if="!isShareShow" class="content animated">
<view @click="showCansel">
<image class="bg1" src="https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/bj1.png" mode="aspectFit"></image>
<image class="bg2" src="https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/bj2.png" mode="aspectFit"></image>
<!-- 左侧菜单栏按钮 -->
<view class="icon" v-if="!isStart">
<u-icon name="list" color="#333333" size="28" @click="iconClick"></u-icon>
</view>
<!-- 香 -->
<view class="sticks">
<view class="sticks-time" :style="'height:'+progress+'rpx'">
<template v-if="isStart">
<image class="vector" src="https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/yan.gif" mode="widthFix"></image>
<image class="light" src="https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/Rectangle.gif" mode="aspectFit"></image>
</template>
</view>
<view class="sticks-end"></view>
<image class="group" src="https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/Group.png"></image>
</view>
</view>
<!-- 分秒倒计时展示 -->
<view class="time" :style="'marginTop:'+timeTop+'rpx'" >
<view class="t-width" @click="countClick" :class="{'animated fadeInDown': isStart,'animated fadeInUp': isCancel}">
<u-count-down
ref="countDown"
:time="time"
format="mm:ss"
:autoStart="false"
millisecond
@change="timeChange"
></u-count-down>
</view>
</view>
<view class="click-start" @click="openInfo" v-if="!isStart">
开始
</view>
<view class="click-start" @click="cancelInfo" v-if="isCancel">
放弃
</view>
<!-- 选择专注时长组件 -->
<u-picker
:show="show"
title="专注时长"
ref="uPicker"
:columns="columns"
@confirm="confirm"
@cancel="cancel"
@change="changeHandler"
confirmColor="#000000"
immediateChange
></u-picker>
<audio id="audio" src="https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/trim.mp3"/>
<!-- 左侧菜单栏 -->
<left-menu ref="leftOpen" :userData="userData"></left-menu>
<!-- 会员弹窗提示 -->
<super-popup ref="superPopup" :userData="userData" @experience="openInfo"></super-popup>
<!-- 雨 林 鸟 播放音乐 -->
<view class="music" v-if="windowSteep>0&&isShowMusic">
<view class="music-flex" v-for="(item, index) in musicList" :key="index" @click="musicClick(item, index)">
<image class="music-img" :src="getMusic(item)" mode="widthFix"></image>
<view class="yuanq" :class="{'yuanq-red': item.isPlay}"></view>
</view>
</view>
</view>
<!-- 打卡完成的图片展示 -->
<view class="share animated" :class="{'fadeIn': isShareShow }" v-if="isShareShow">
<image class="image2" src="https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/cha.png" @click="closedShare"></image>
<view style="height: 180rpx;"></view>
<view class="image" id="htmlCanvas">
<view class="canval-text">
<view class="yanyu">{{chanyu}}</view>
</view>
<view class="author">{{auther}}</view>
<view style="width: 361rpx;"></view>
</view>
<!-- 下载图片 -->
<image @click="renderScript.emitData" class="image3" src="https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/xiazai.png"></image>
</view>
</view>
</template>
<script>
import superPopup from '@/components/super-popup/super-popup.vue'
// 定义全局播放器
var musicSelect = null;
musicSelect = uni.createInnerAudioContext(); //创建时间选择播放器对象 选择时间播放机械声
/*
"ambient" - 不中止其他声音播放,不能后台播放,静音后无声音;
"soloAmbient" - 中止其他声音播放,不能后台播放,静音后无声音;
"playback" - 中止其他声音,可以后台播放,静音后有声音。
*/
musicSelect.sessionCategory = "ambient"
musicSelect.src = "https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/trim.mp3";
var music = null;
music = uni.createInnerAudioContext(); //创建雨林鸟播放器对象
// music.sessionCategory = "ambient"
music.src = "https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/yu-music.mp3";
export default {
components: {
superPopup
},
data() {
return {
windowSteep:10,//窗口未点击事件数
windowTime:null,//窗口点击的时间
timeTop:154,//点击开始时间数字的上边距
timeTwo:null,//点击开始时间数字的动画
musicList: [
{
id: 1,
isPlay: true, //是否播放雨林鸟音乐
black: 'https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/yu-black.png',
grey: 'https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/yu-g.png',
music: 'https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/yu-music.mp3'
},
{
id: 2,
isPlay: false,
black: 'https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/lin-black.png',
grey: 'https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/lin-g.png',
music: 'https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/lin-music.mp3'
},
{
id: 3,
isPlay: false,
black: 'https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/niao-black.png',
grey: 'https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/niao-g.png',
music: 'https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/niao-music.mp3'
}
], //雨林鸟未播放图标地址
musicIndex: 0,
show: false,
columns: [
[5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120],
[
'00','01','02','03','04','05','06','07','08','09','10',
'11','12','13','14','15','16','17','18','19','20',
'21','22','23','24','25','26','27','28','29','30',
'31','32','33','34','35','36','37','38','39','40',
'41','42','43','44','45','46','47','48','49','50',
'51','52','53','54','55','56','57','58','59',]
],
minute: 0,
second: 0,
time: 900000, //展示的分钟和秒
indexs: [],
progress: 400, //进度条高度
isStart: false, //其他操作按钮是否隐藏
isShareShow: false, //下载图片页面 是否展示
isCancel: false, //放弃 按钮 是否显示
isShowMusic: false, //是否显示音乐按钮
chanyu: '',
auther: '',
id: '',
userData:{}
}
},
onShow(){
this.userData = uni.getStorageSync('userData')
},
onUnload() {
if(this.windowTime){
clearInterval(this.windowTime)
}
},
computed: {
/*
@param {Number} index 当前音乐索引 0代表'雨', 1'林', 2'鸟'
动态展示对应的文字的图片(已选择和未选择的音乐)
*/
getMusic() {
return (item) => {
if(item.isPlay) {
return item.black
} else {
return item.grey
}
}
}
},
methods: {
/*
如果windowSteep = 10表表示屏幕刚点击完的状态,
十秒之后音乐选择自动关闭,
如果屏幕点击则再次初始化为10,重新开始计时
*/
windowClick(){
if(!this.isStart){
return
}
if(this.windowTime){
clearInterval(this.windowTime)
}
this.windowSteep = 10
this.windowTime = setInterval(()=>{
this.windowSteep--
if(this.windowSteep<=0){
clearInterval(this.windowTime)
}
},1000)
},
// 点击弹出时间选择
countClick() {
if(!this.isStart) {
this.show = true
}
},
// 点击屏幕
showCansel() {
// 如果时间开始倒数 点击屏幕则显示放弃按钮
if(this.isStart) {
this.timeTop = 154
this.isCancel = true
}
},
// 点击放弃按钮
cancelInfo() {
// this.time = 900000 //初始默认值
this.$refs.countDown.pause();
this.$refs.countDown.reset();
this.isShowMusic = false
music.pause()
this.musicList[1].isPlay = false
this.musicList[2].isPlay = false
this.isStart = false
this.isCancel = false
clearInterval(this.windowTime)
},
// 点击开始
openInfo(val){
if(uni.getStorageSync('token') === '') {
uni.showToast({
icon:"none",
title:"请先登录!"
})
setTimeout(() => {
uni.navigateTo({
url: '/pages/login/login'
})
},1000)
return
}
this.$http.get("/common/user/info").then(res=>{
uni.setStorageSync('userData',res.data)
this.userData = res.data
})
// valid_end会员结束时间
let valid_end = new Date(this.userData.valid_end)
let date = new Date()
if(valid_end.getTime() < date.getTime() || !this.userData.valid_end){
// 弹出会员非会员弹窗 非体验
if(val != 'experience'){
this.$refs.superPopup.open()
return
}
}
// 显示音乐按钮 并默认开始播放雨音效
this.musicList.filter(e => {
if(e.id === 1) {
e.isPlay = true
} else {
e.isPlay = false
}
})
this.isShowMusic = true
music.src = "https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/yu-music.mp3";
music.play()
music.onEnded(() => {
//播放结束 循环播放
music.play()
});
this.isStart = true
this.timeTop = 154
this.timeTwo = setInterval(()=>{
this.timeTop+=5
if(this.timeTop>=256){
clearInterval(this.timeTwo)
}
},20)
// this.windowClick()
this.$refs.countDown.start();
},
// 监听倒计时change
timeChange(e) {
// 计算百分比
let all = (e.hours * 60 * 60 * 1000) + (e.minutes * 60 * 1000) + (e.seconds * 1000)
let a = this.time;
let b = Number(all)/Number(a);
let c = b * 400
this.progress = c.toFixed()
if(this.progress == 0) {
this.isStart = false
this.isShareShow = true
this.time = 0
clearInterval(this.windowTime)
music.pause()
// 随机获取一条禅语
this.$http.get('/time/chanyu/random').then(res => {
if(res.code === 0) {
this.id = res.data.id
this.chanyu = res.data.content
this.auther = res.data.name
// 打卡完成
this.$http.post('/time/record/add', {
chan_id: this.id,
status: 3, //1-已开始 2-暂停 3-完成 4-取消
time: (this.minute * 60) + this.second
}).then(res => {
if(res.code !== 1) {
uni.showToast({
icon: 'error',
title: res.msg
})
}
})
} else {
uni.showToast({
icon: 'none',
title: res.msg
})
}
})
}
},
// 监听变化 播放音效
changeHandler(e) {
this.indexs = e.indexs
musicSelect.play(); //执行播放
},
// 回调参数为包含columnIndex,value,values
confirm(e) {
musicSelect.pause()
this.minute = e.value[0]
this.second = Number(e.value[1])
this.time = (this.minute * 60 * 1000) + (this.second * 1000)
this.show = false
},
cancel() {
musicSelect.pause()
this.show = false
},
// 左侧菜单栏弹出
iconClick() {
this.$refs.leftOpen.open()
},
// 关闭图片展示
closedShare() {
this.timeTop = 154
this.progress = 400
this.isShareShow = false
this.isCancel = false
this.isShowMusic = false
music.pause()
// this.time = 900000 //初始默认值
this.time = (this.minute * 60 * 1000) + (this.second * 1000)
this.$http.get("/common/user/info").then(res=>{
uni.setStorageSync('userData',res.data)
this.userData = res.data
})
},
// 画出图片并保存到本地相册
receiveRenderData(val) {
uni.showLoading({
title:"下载中"
})
let that=this
let base64 = val
const bitmap = new plus.nativeObj.Bitmap("test");
bitmap.loadBase64Data(base64, function() {
const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式
bitmap.save(url, {
overwrite: true, // 是否覆盖
// quality: 'quality' // 图片清晰度
}, (i) => {
uni.saveImageToPhotosAlbum({
filePath: i.target,
success: function() {
uni.hideLoading()
uni.showToast({
title: '图片保存成功',
icon: 'none'
})
bitmap.clear()
}
});
}, (e) => {
uni.hideLoading()
uni.showToast({
title: '图片保存失败',
icon: 'none'
})
bitmap.clear()
});
}, (e) => {
uni.hideLoading()
uni.showToast({
title: '图片保存失败',
icon: 'none'
})
bitmap.clear()
});
},
// 点击雨林鸟播放或者暂停音乐
musicClick(item,index) {
// isPlay控制是否选中的状态
this.musicList.filter(e => {
if(e.id !== item.id) {
e.isPlay = false
} else {
e.isPlay = !e.isPlay
}
})
music.src = item.music;
// 如果isPaly为true则播放当前音乐 暂停其他音乐
if(item.isPlay) {
// 播放
music.play()
music.onEnded(() => {
//播放结束 循环播放
music.play()
});
} else {
// 暂停
music.pause()
}
},
}
}
</script>
<script module="renderScript" lang="renderjs">
import html2canvas from '@/util/html2canvas.js';
export default {
data() {
return {
}
},
mounted() {},
methods: {
// 发送数据到逻辑层
emitData(e, ownerVm) {
const dom = document.getElementById('htmlCanvas')
html2canvas(dom, {
width: dom.clientWidth, //dom 原始宽度
height: dom.clientHeight,
scrollY: 0, // html2canvas默认绘制视图内的页面,需要把scrollY,scrollX设置为0
scrollX: 0,
dpi:300,
useCORS: true, //支持跨域,但好像没什么用
allowTaint: false
}).then((canvas) => {
// 将生产的canvas转为base64图片3
ownerVm.callMethod('receiveRenderData', canvas.toDataURL('image/png'))
});
}
}
};
</script>
<style lang="scss" scoped>
.pages{
height: 100vh;
overflow: hidden;
}
.hidden {
display:none
}
.content {
// position: relative;
// margin: 0;
height: 100vh;
position: absolute;
left: 0;
right: 0;
}
.bg1 {
position: absolute;
top: 0;
right: 0;
}
.bg2 {
position: absolute;
height: 1000rpx;
left: 0;
bottom: 0;
z-index: 0;
}
.icon {
position: absolute;
top: 90rpx;
left: 50rpx;
z-index: 99;
}
.sticks {
position: relative;
height: calc(100vh - 450rpx);
.sticks-time {
position: absolute;
left: 50%;
bottom: 136rpx;
transform: translate(-50%);
height: 400rpx;
width: 12rpx;
background: #000000;
border-radius: 90rpx;
z-index: 20;
.vector {
position: absolute;
top: -260rpx;
left: 50%;
transform: translate(-62%);
width: 172rpx;
height: 452rpx;
z-index: 30;
}
.light {
position: absolute;
top: -18rpx;
width: 12rpx;
height: 20rpx;
z-index: 30;
}
}
.sticks-end {
position: absolute;
left: 50%;
bottom: 0;
transform: translate(-50%);
width: 4rpx;
height: 150rpx;
background: #333333;
border-radius: 90rpx;
z-index: 10;
}
.group {
position: absolute;
left: 50%;
bottom: -76rpx;
transform: translate(-50%);
width: 354rpx;
height: 144rpx;
}
}
.time {
position: relative;
z-index: 99;
display: flex;
align-items: center;
justify-content: center;
margin-top: 156rpx;
.t-width {
width: 300rpx;
}
}
.m-t-264 {
margin-top: 264rpx;
}
.m-t-156 {
margin-top: 156rpx;
}
/deep/ .u-count-down .u-count-down__text{
font-style: normal;
font-weight: 900;
font-size: 60rpx;
line-height: 48rpx;
text-align: center;
letter-spacing: 0.2em;
color: #000000;
}
.click-start {
margin: 0 auto;
text-align: center;
font-style: normal;
font-weight: 400;
font-size: 32rpx;
line-height: 48rpx;
letter-spacing: 0.2em;
color: #FFFFFF;
background-position: 36rpx;
background-image: url('https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/start-bg.png');
background-size: 419rpx 80rpx;
width: 419rpx;
height: 80rpx;
background-repeat: no-repeat;
padding-top: 10rpx;
margin-top: 60rpx;
position: relative;
z-index: 50;
}
.share {
height: 100vh;
// box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
// position: absolute;
// z-index: 999;
.image {
width: 722rpx;
height: 552rpx;
padding: 90rpx 76rpx 38rpx;
box-sizing: border-box;
background: url('https://majia-time-app.oss-cn-hangzhou.aliyuncs.com/img/crad_img.png');
background-size: 100% 100%;
box-shadow: 0 6rpx 13rpx 0 rgba(0,0,0,0.08);
position: relative;
}
.m-t-88 {
margin-top: 162rpx;
}
.image2 {
position: absolute;
top: 60rpx;
right: 40rpx;
width: 44rpx;
height: 44rpx;
}
.image3 {
position: absolute;
left: 50%;
bottom: 150rpx;
transform: translate(-50%);
width: 132rpx;
height: 132rpx;
}
.canval-text {
width: 361rpx;
font-size: 32rpx;
font-weight: 900;
color: #414141;
line-height: 50rpx;
writing-mode:vertical-lr;
letter-spacing: 4rpx;
.yanyu {
height: 220rpx;
}
}
.author {
font-size: 32rpx;
font-weight: 900;
color: #414141;
line-height: 50rpx;
writing-mode:vertical-lr;
letter-spacing: 6rpx;
position: absolute;
bottom: 36rpx;
right: 53%;
}
}
.music {
position: absolute;
right: 0;
bottom: 50%;
transform: translate(-50%);
height: 214rpx;
display: flex;
flex-direction: column;
justify-content: space-between;
.w-picker-view{
width: 100rpx;
}
.music-flex {
display: flex;
align-items: center;
.music-img {
width: 36rpx;
height: 36rpx;
}
}
.yuanq {
margin-left: 14rpx;
width: 19rpx;
height: 19rpx;
background: #FFFFFF;
border-radius: 50%;
border: 2rpx solid #EDEDED;
}
.yuanq-red {
border: 2rpx solid #C24229;
}
}
</style>
<style>
page {
position: relative;
background: #EAEAEA;
}
</style>
到了这里,关于uniapp使用uni.createInnerAudioContext()播放指定音频并且切换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!