1、web音频 Web Audio API
const audioUrl = `https://assets.mixkit.co/music/preview/mixkit-hazy-after-hours-132.mp3`;const play_button = document.querySelector("play_button");const pause_button = document.querySelector("pause_button");class Demo { constructor() { this.audioContext = new AudioContext({ latencyHint: "balanced" }); this.audioSourceNode = null; this.audioBuffer = null; this.analyser = null; this.bufferLength = null; this.dataArray = null; this.scriptProcessor = null; this.gainNode = null; this.draw = null; this.canvas = null; this.canvasCtx = null; this.loading = false; this.playing = false; this.WAVFormatInfo = null; } async start(url) { this.loading = true; const musicArrayBuffer = await fetch(url).then((res) => res.arrayBuffer()); // this.initGain(); // this.initAnalyser(); this.audioContext.decodeAudioData(musicArrayBuffer).then( (decodedData)=>{ this.loading = false; this.playing = true; this.audioBuffer = decodedData; this.play(decodedData) } ); } async play (buffer) { if(buffer ?? this.audioBuffer){ this.audioSourceNode = this.audioContext.createBufferSource(); this.audioSourceNode.buffer = buffer ?? this.audioBuffer; this.audioSourceNode.connect(this.audioContext.destination); // this.audioSourceNode.connect(this.analyser); // this.audioSourceNode.connect(this.gainNode); this.audioSourceNode.start(0); } } async pause() { if(this.audioSourceNode){ this.audioSourceNode.stop(); this.playing = false } } initGain () { this.gainNode = this.audioContext.createGain(); } initAnalyser () { this.analyser = this.audioContext.createAnalyser(); //快速傅里叶变换参数 this.analyser.fftSize = 256; //bufferArray长度 this.bufferLength = this.analyser.frequencyBinCount; //创建bufferArray,用来装音频数据 this.dataArray = new Uint8Array(this.bufferLength); }}const musicDemo = new Demo();play_button.onclick = () => musicDemo.start(audioUrl);pause_button.onclick = () => musicDemo.pause();
2、web 语音 Web Speech API
1. 语音合成 SpeechSynthesis
let speechInstance = new SpeechSynthesisUtterance('大家好,我是渣渣辉。');speechSynthesis.speak(speechInstance);
附录