/
MicAudioContext.vue
100 lines (90 loc) · 2.86 KB
/
MicAudioContext.vue
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<template>
<div>
<h1>@bigear/microphone-recorder</h1>
<p> npm : <a href='https://www.npmjs.com/package/@bigear/microphone-recorder'>https://www.npmjs.com/package/@bigear/microphone-recorder </a> </p>
<!-- Draw the action buttons -->
<button id='start-btn' v-on:click='handleClickStart'>Start recording</button>
<button id='stop-btn' v-on:click='handleClickStop' disabled>Stop recording</button>
<ul id='recordingslist'></ul>
</div>
</template>
<script>
import Recorder from '@bigear/microphone-recorder'
const DEFAULT_AUDIO_FORMAT = 'audio/wav'
export default {
data: function() {
return {
audio_stream: null,
audio_context: null,
recorder: null
}
},
mounted() {
this.Initialize()
},
methods: {
Initialize: function() {
try {
window.AudioContext = window.AudioContext || window.webkitAudioContext
window.URL = window.URL || window.webkitURL
this.audio_context = new AudioContext()
} catch (e) {
alert('No web audio support in this browser!')
}
},
stopRecording: function(callback) {
const { recorder, audio_stream } = this
recorder && recorder.stop()
audio_stream.getAudioTracks()[0].stop()
// Disable Stop button and enable Record button !
document.getElementById('start-btn').disabled = false
document.getElementById('stop-btn').disabled = true
if (typeof callback == 'function') {
recorder.exportWAV(DEFAULT_AUDIO_FORMAT, function(blob) {
callback(blob)
recorder.clear()
})
}
},
appendBlobToListItem: function(AudioBLOB) {
const url = URL.createObjectURL(AudioBLOB)
const li = document.createElement('li')
const au = document.createElement('audio')
const hf = document.createElement('a')
au.controls = true
au.src = url
hf.href = url
hf.download = new Date().toISOString() + '.wav'
hf.innerHTML = hf.download
li.appendChild(au)
li.appendChild(hf)
document.getElementById('recordingslist').appendChild(li)
},
handleClickStop: function() {
this.stopRecording(this.appendBlobToListItem)
},
handleClickStart: function() {
const { audio_context } = this
navigator.mediaDevices.getUserMedia({ audio: true }).then((mediaStreamObject)=>{
this.audio_stream = mediaStreamObject
const input = audio_context.createMediaStreamSource(mediaStreamObject)
const recorder = new Recorder(input)
recorder && recorder.record()
this.recorder = recorder
document.getElementById('start-btn').disabled = true
document.getElementById('stop-btn').disabled = false
})
}
},
asyncData({ store }) {}
}
</script>
<style>
ul {
list-style: none;
}
#recordingslist audio {
display: block;
margin-bottom: 10px;
}
</style>