目录
一、背景:
二、具体解决方法
一、背景:
angular 调用 MediaRecorder 来使用麦克风获取声音,(具体要求:angular 前端 按键调用 麦克风,松开按键生成音频文件)代码如下(来自通义千问)
----- HTML ------------------
<button (mousedown)="startRecording()" (mouseup)="stopRecording()">Record</button>
<audio #audioPlayer controls></audio>
---- Typescrip -----------------------
import { Component, OnInit, ViewChild } from '@angular/core';Component({selector: 'app-recorder',templateUrl: './recorder.component.html',styleUrls: ['./recorder.component.css']
)
xport class RecorderComponent implements OnInit {@ViewChild('audioPlayer') audioPlayer;private chunks = [];private mediaRecorder;private stream;constructor() {}ngOnInit() {// 请求麦克风权限navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {this.stream = stream;this.mediaRecorder = new MediaRecorder(stream);this.mediaRecorder.addEventListener('dataavailable', this.handleDataAvailable.bind(this));});}startRecording() {this.mediaRecorder.start();}stopRecording() {this.mediaRecorder.stop();this.chunks = [];this.stream.getTracks().forEach(track => track.stop());}handleDataAvailable(event) {if (event.data.size > 0) {this.chunks.push(event.data);}}downloadBlob(blob: Blob) {const url = window.URL.createObjectURL(blob);const a = document.createElement('a');document.body.appendChild(a);a.style = 'display: none';a.href = url;a.download = 'recording.wav';a.click();window.URL.revokeObjectURL(url);}ngAfterViewInit() {this.mediaRecorder.addEventListener('stop', () => {const blob = new Blob(this.chunks, { type: 'audio/wav' });this.downloadBlob(blob);this.audioPlayer.nativeElement.src = URL.createObjectURL(blob);});}
}
编译报错:Cannot find name 'MediaRecorder'
找了半天都说 MediaRecorder 是 Web API ,不存在依赖问题,只要在 tsconfig.json 上面配上 "lib": ["dom", "es2018"] 就可以了,试了还是不行
后面找到了一篇文章,说要加上 type 和 安装 @types/dom-mediacapture-record
【量角器单元测试角不适用于MediaRecorder:量角器单元测试角不适用于MediaRecorder-腾讯云开发者社区-腾讯云,
原文:Protractor unit tests Angular does not work with MediaRecorder:Protractor unit tests Angular does not work with MediaRecorder - Stack Overflow】
二、具体解决方法
以下只是我尝试之后,编译不再报错了的解决方法。本人对 angular 的各种属性还不太熟悉,所以只是把报错解决了,不一定能解决实际问题。
① 安装 @types/dom-mediacapture-record
npm install --save-dev @types/dom-mediacapture-record
② tsconfig.json 加上 dom.iterable
"lib": ["dom", "dom.iterable", "es2018"],
③ tsconfig.app.json 加上 "types": ["node", "dom-mediacapture-record"]
④ 以 ssl 方式启动
ng serve --configuration=dev --port 4205 --host 0.0.0.0 -o ---ssl true