首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角2中的WebAudio ScriptProcessor

角2中的WebAudio ScriptProcessor
EN

Stack Overflow用户
提问于 2017-05-18 22:12:03
回答 1查看 442关注 0票数 1

我需要在角度2中动态生成音频,我找到了一个与WebAudio一起工作的示例,但在JS中。在JS中,一切都运行得很好,我今天可以为TS (角2)播放一些声音(例如随机噪声)。问题是,我需要访问服务中的变量,但需要访问脚本处理器事件(onaudioprocess)。下面有一个示例代码。

这有可能吗?在JS中,我有全局变量,并且工作得很好。

进口..。

代码语言:javascript
复制
@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;
      }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-18 22:56:49

这也是多年来困扰JS的人的问题。不能直接使用this.generateSounds作为回调,因为它将失去this绑定。试试这个:

代码语言:javascript
复制
this.jsProcessor.onaudioprocess = this.generateSounds.bind(this);

或(等同):

代码语言:javascript
复制
this.jsProcessor.onaudioprocess = (event: any) => {
  this.generateSounds(event);
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44058559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档