# 关于播放pc本地音乐
一开始尝试用uni本身的chooseFile然后createInnerAudioContext播放,发现不可以,路径读不到对应的音乐,然后搜索了很多文章和解决方案,有开一个python服务返回文件夹下所有音乐列表的,然后node去读文件等等,最后看到使用h5特性,原生js(AudioContext)播放很方便好用,然后也改良了一个uni版本的,在web前端模块我有记录。
弄好了以后,突然再想用createInnerAudioContext试一试,结果竟然就好用了,我。。。。。。无了个大语,绕了一圈竟然最简单就能实现了?然后打包h5测试了一下electron也好用,ok完美解决
<template>
<view >
当前音乐:<button @click="selectmusic">{{musicNameStr}}</button>
<button @click="playAudio">播放音乐</button>
</view>
</template>
<script>
import songmp3 from "@/static/gudusongge.mp3"
var context = null;
export default {
data() {
return {
innerAudioContext:null, //全局
musicNameStr:"默认音乐--孤独颂歌",
musicStr:songmp3,
}
},
onLoad() {
this.innerAudioContext = uni.createInnerAudioContext();
this.innerAudioContext.src = this.musicStr;
// this.innerAudioContext.src = 'https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-hello-uniapp/2cc220e0-c27a-11ea-9dfb-6da8e309e0d8.mp3';
this.innerAudioContext.volume = 1;
this.innerAudioContext.loop = true;
},
methods: {
selectmusic(){
let that =this
uni.chooseFile({
count: 1, //默认100
extension:['.mp3','.mp4'],
success: function (res) {
// console.log(res)
that.musicStr = res.tempFilePaths[0]
that.musicNameStr = res.tempFiles[0].name
that.innerAudioContext.src = that.musicStr
// console.log(innerAudioContext)
}
});
},
//播放音频
playAudio() {
if(this.isPlay){
return ;
}else{
this.isPlay = true
this.innerAudioContext.play();
}
},
//停止音频
stopAudio() {
this.isPlay = false
this.innerAudioContext.stop();
},
}
}
</script>
1
2
3
4
5
6
7
8
9
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
60
61
62
63
64
65
66
2
3
4
5
6
7
8
9
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
60
61
62
63
64
65
66