基于elctron+vue+ts实现的录音音量实时分析,给用户一个友好交互提示。
![](https://img.haomeiwen.com/i18796137/cb0f69d8d285624e.png)
![](https://img.haomeiwen.com/i18796137/54955cbbbd61cf40.png)
核心片段分享:
const status = remote.systemPreferences.getMediaAccessStatus('microphone')
if (status == 'granted') {
const constrains = { audio: true }
navigator.mediaDevices
.getUserMedia(constrains)
.then((stream) => {
// console.log(stream)
this.openRecordSuccess(stream)
})
.catch((err) => {
this.openRecordError(err)
})
}
openRecordSuccess(stream: unknown): void {
this.audioContext = new AudioContext()
this.analyser = this.audioContext.createAnalyser()
this.microphone = this.audioContext.createMediaStreamSource(stream as MediaStream)
this.recordEventNode = this.audioContext.createScriptProcessor(2048, 1, 1)
this.analyser.smoothingTimeConstant = 0.8
this.analyser.fftSize = 1024
this.microphone.connect(this.analyser)
this.analyser.connect(this.recordEventNode)
this.recordEventNode.connect(this.audioContext.destination)
this.recordEventNode.addEventListener('audioprocess', this.analyzeMicrophoneVolume)
}
openRecordError(error: unknown): void {
console.log('访问用户媒体设备失败:', error)
}
analyzeMicrophoneVolume(): void {
const array = new Uint8Array(this.analyser.frequencyBinCount)
this.analyser.getByteFrequencyData(array)
let values = 0
const length = array.length
for (let i = 0; i < length; i++) {
values += array[i]
}
const average = values / length
this.recordVolume = average
// console.log('音量大小:' + Math.round(average))
}
网友评论