# uniapp版h5选择本地音乐播放

集成uni版的话就是如下代码,这样主要是为了electron方便使用,只是createBufferSource(AudioBufferSourceNode)这玩意没有正在播放状态,只能手动管理播放状态

<template>
	<view class="content">
		
		当前音乐:<button @click="music">{{musicNameStr}}</button>
		
		<button @click="playSound">播放音乐</button>
	</view>
</template>

<script>
	var context = null;
	export default {
		data() {
			return {
				musicNameStr:"默认音乐--孤独颂歌",
				musicStr:"",
				filename:"",
				mbuffer:null,
			}
		},
		onLoad() {
			
			
		},
		methods: {
			music(){
				let that =this
				uni.chooseFile({
				  count: 6, //默认100
				  extension:['.mp3','.mp4'],
					success: function (res) {
						console.log(res)
						that.musicStr = res.tempFiles[0]
						
						that.musicNameStr = that.musicStr.name
						
						
						let music = uni.createInnerAudioContext(); //创建播放器对象
						 
						  var read = new FileReader();
						  context = new (window.AudioContext || window.webkitAudioContext)();
						  console.log(context)
						  read.onload = function() {
							  // 将arrayBuffer转成audioBuffer
							  context.decodeAudioData(this.result, function(buffer) {
								  
								   that.mbuffer= buffer;
								   console.log(that.mbuffer)
								  // that.playSound();
							  }, function() {
								  console.log('error');
							  });
						  };
						read.readAsArrayBuffer(that.musicStr);
						  
						
					}
				});
			},
			playSound() {
			    var source = context.createBufferSource();
				console.log(source)
			    // 设置数据
			    source.buffer = this.mbuffer;
				source.loop = true; //循环播放
			    // connect到扬声器
			    source.connect(context.destination);
			    source.start();
			}
		}
	}
</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
67
68
69
70
71
72
73
74
75