0

希望从我在设备访问组件路由上实现的音量计中释放 CPU 资源。navigator.mediaDevices.getUserMedia此音量计组件使用 WebRTC调用获取在父组件(设备访问)中设置的现有流。父组件允许用户切换音频输入设备并让音量表反映音量表中反映的输入音量/增益/反馈。

目前存在一个问题,在设备的多个交换机上,CPU 级别逐渐上升。此外,此设备访问页面是通向视频会议组件的网关。一个常见的场景是让用户回到这个除冰访问页面。当用户返回时,onaudioprocess 仍在运行并增加 CPU 使用率。

以下是代码。我在子组件(体积计)中实现了一个 ngOnDestroy,但它似乎并没有影响仍在运行的进程。当我切换输入音频设备(在订阅中)时,我想杀死脚本处理器并重新启动它。我该怎么做呢?

export class VolumeMeterComponent implements OnInit, AfterViewInit, OnDestroy {

  private stream: MediaStream = null;
  private audioContext: AudioContext = null;
  private meter: any = null;
  private canvasContext: any = null;
  // height and width of the volume meter
  private WIDTH: number = 146;
  private HEIGHT: number = 9;
  private rafID: number = null;
  private mediaStreamSource: any = null;
  private clipping: boolean = null;
  private lastClip: number = null;
  private volume:number = null;
  // averaging: how "smoothed" you would like the meter to be over time.  
  // Should be between 0 and less than 1.
  private averaging: number = .95;
  // the level (0 to 1) that you would consider "clipping"
  private clipLevel: number = .98;
  // clipLag: how long you would like the "clipping" indicator to show after clipping has occurred, in milliseconds.
  private clipLag: number = 750;
  private loopInstance: any = null;
  private processHandle: any = null;
  // @ts-ignore
  @ViewChild('meterElement', {read: ElementRef, static: false}) meterElement: ElementRef;

  constructor(private streamService: StreamService) {}

  ngOnInit(): void {
    // nothing here for now
  }

  ngAfterViewInit(): void {
    this.streamService.stream$.subscribe(stream =>{
      this.stream = stream;
      if (this.loopInstance) {
        this.processHandle.stop();
        this.cleanupMeterOnChange();
      }
      this.initializeMeter();
    });
  }

  ngOnDestroy(): void {
    this.cleanupMeterOnChange();
  }

  cleanupMeterOnChange():void {
    // cleanup the canvasContext and meter onDestroy
    // best practice is to cleanup the the canvasContext as it has processes
    this.meter = null;
    this.canvasContext = null;
    this.drawLoop = null;
  }

  initializeMeter():void {
    this.canvasContext = this.meterElement.nativeElement.getContext('2d');
    // update audioContext to whatever is available from browser
    try {
      (window as any).AudioContext = (window as any).AudioContext || (window as any).webkitAudioContext;
      this.audioContext = new AudioContext();
      this.mediaStreamSource = this.audioContext.createMediaStreamSource(this.stream);
      // Create a new volume meter and connect it.
      this.meter = this.createAudioMeter(this.audioContext);
      this.mediaStreamSource.connect(this.meter);
      this.loopInstance = this.drawLoop();
    } catch(error) {
      console.log('Error setting up the volume meter. ' + error);
    }
  }

  drawLoop = () => {
    // clear the background
    this.canvasContext.clearRect(0, 0, this.WIDTH, this.HEIGHT);
    // check if we're currently clipping
    if (this.meter.checkClipping()) {
      this.canvasContext.fillStyle = 'red';
    } else {
      this.canvasContext.fillStyle = 'green';
    }
    // draw a bar based on the current volume
    this.canvasContext.fillRect(0, 0, this.meter.volume * this.WIDTH * 1.4, this.HEIGHT);

    // set up the next visual callback
    this.rafID = window.requestAnimationFrame( this.drawLoop );
  }

  createAudioMeter = audioContext => {
    const processor = audioContext.createScriptProcessor(2048, 1, 1);
    processor.onaudioprocess = this.volumeAudioProcess;
    this.processHandle = processor;
    processor.clipping = false;
    processor.lastClip = 0;
    processor.volume = 0;
    processor.clipLevel = this.clipLevel;
    processor.averaging = this.averaging;
    processor.clipLag = this.clipLag;

    // this will have no effect, since we don't copy the input to the output,
    // but works around a current Chrome bug.
    processor.connect(audioContext.destination);
    processor.checkClipping =
      checkClipping;

    // tslint:disable-next-line:typedef
    function checkClipping() {
      const that = this;
      if (!that.clipping) {
        return false;
      }

      if ((that.lastClip + that.clipLag) < window.performance.now()) {
        that.clipping = false;
      }
      return that.clipping;
    }

    processor.shutdown =
      function(): void {
        this.disconnect();
        this.onaudioprocess = null;
      };

    return processor;
  }

  volumeAudioProcess( event ): void {
    this.clipping = false;
    const buf = event.inputBuffer.getChannelData(0);
    const bufLength = buf.length;
    let sum = 0;
    let x;

    // Do a root-mean-square on the samples: sum up the squares...
    for (let i = 0; i < bufLength; i++) {
      x = buf[i];
      if (Math.abs(x) >= this.clipLevel) {
        this.clipping = true;
        this.lastClip = window.performance.now();
      }
      sum += x * x;
    }

    // ... then take the square root of the sum.
    const rms =  Math.sqrt(sum / bufLength);

    // Now smooth this out with the averaging factor applied
    // to the previous sample - take the max here because we
    // want "fast attack, slow release."
    this.volume = Math.max(rms, this.volume * this.averaging);
  }
}

组件标记:

<canvas id="meterElement" #meterElement width="146" height="8"></canvas>
<p class="level-label">Microphone volume level</p>

我曾尝试使用 ViewChild 订阅画布并取消订阅,但运气不佳。任何人都对更有效地运行它的策略有任何见解。订阅drawLoop(并将其提取到服务中)是最好的答案吗?

我知道 WebRTC 推荐 audioWorklets: https ://alvestrand.github.io/audio-worklet/

  • 这是一个草稿,没有被 Safari 采用。从长远来看,这似乎是一个更好的解决方案。
4

1 回答 1

0

你可以调用close()AudioContext 来停止它的所有节点,并让它释放它需要用来做它的事情的任何系统资源。我认为将其添加到您的cleanupMeterOnChange()方法中应该可以提高性能。

cleanupMeterOnChange():void {
    // ...
    this.audioContext.close();
}
于 2020-12-23T15:13:42.620 回答