我需要在角度2中动态生成音频,我找到了一个与WebAudio一起工作的示例,但在JS中。在JS中,一切都运行得很好,我今天可以为TS (角2)播放一些声音(例如随机噪声)。问题是,我需要访问服务中的变量,但需要访问脚本处理器事件(onaudioprocess)。下面有一个示例代码。
这有可能吗?在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;
}发布于 2017-05-18 22:56:49
这也是多年来困扰JS的人的问题。不能直接使用this.generateSounds作为回调,因为它将失去this绑定。试试这个:
this.jsProcessor.onaudioprocess = this.generateSounds.bind(this);或(等同):
this.jsProcessor.onaudioprocess = (event: any) => {
this.generateSounds(event);
};https://stackoverflow.com/questions/44058559
复制相似问题