1

공중에서 각도 2로 오디오를 생성해야하고 WebAudio를 사용하지만 JS에서는 작동하는 샘플을 발견했습니다. JS에서 모든 것이 잘 작동했으며 TS (Angular 2)에 대한 일부 사운드 (예 : 랜덤 노이즈)를 재생할 수있었습니다. 것은 내 서비스에서하지만 스크립트 프로세서 이벤트 (onaudioprocess)에서 가지고있는 변수에 액세스해야한다는 것이다. 아래 샘플 코드가 있습니다.WebAudio의 ScriptProcessor (각도 2)

이것이 가능할까요? JS에서 전역 변수를 갖고 잘 작동했습니다.

수입 ...

@Injectable() 
export class SomeService { 
    variable: any; 
    constructor() 
    { 
    this.variable = new Variable(); 
    this.initWebAudio(); 
    } 

    initWebAudio(): void 
    { 
     try { 
      this.context = new ((<any>window).AudioContext || (<any>window).webkitAudioContext)(); 
      this.context.SampleRate = this.sample_rate; 

      this.masterGainNode = this.context.createGain(); 
      this.masterGainNode.gain.value = 0.5; 
      this.masterGainNode.connect(this.context.destination); 

      this.startJSProcessor(); 
      } 
      catch(e) { 
      alert('Web Audio API is not supported in this browser'); 
      }  
    } 

    startJSProcessor(): void 
    {  
     if(this.context.createScriptProcessor) 
     { 
      this.jsProcessor = this.context.createScriptProcessor(4096, 1, 2); 
      //alert("Chrome Desktop/Android"); 
     } 
     else if(this.context.createJavaScriptNode) 
     { 
      this.jsProcessor= this.context.createJavaScriptNode(4096,1,2); 
      //alert("Safari"); 
     } 
     else 
     { 
      alert("No way"); 
     }   
     this.jsProcessor.onaudioprocess = this.generateSounds; 
     this.jsProcessor.connect(this.masterGainNode); 
    } 

    generateSounds(event: any): void 
    {  
     var outputR = event.outputBuffer.getChannelData(0); 
     var outputL = event.outputBuffer.getChannelData(1);  

     //"this" is undefined here...  
     var something = this.variable.something; 
     } 

답변

2

이 몇 년 동안 JS 사람들을 flummoxing 된 것 같은 문제입니다. this 바인딩이 손실되므로 this.generateSounds을 콜백으로 직접 사용할 수 없습니다. 이 시도 :

this.jsProcessor.onaudioprocess = this.generateSounds.bind(this); 

또는 (동등한) :

this.jsProcessor.onaudioprocess = (event: any) => { 
    this.generateSounds(event); 
}; 
+0

예, 맞습니다. 나는 이것을 시도하고 지금 작동합니다. –