I put together a function that plays some tones, however, I can hear from time to time some weird artifacts. I'm new to the Web Audio API, and I don't know if I'm doing things correctly. I'd appreciate suggestions.
Here is my code:
export class ToneService {
tone = 310;
audioContext!: AudioContext;
playSequenceSound() {
// console.log(this.tone, 'tone');
const sequence = [310, 330, 350, 370, 390, 410, 430];
if (!this.audioContext) {
this.audioContext = new AudioContext();
}
const oscillator = this.audioContext.createOscillator();
oscillator.type = 'sine';
const gainNode = this.audioContext.createGain();
gainNode.gain.value = 0.05;
oscillator.connect(gainNode);
gainNode.connect(this.audioContext.destination);
oscillator.frequency.setValueAtTime(
this.tone,
this.audioContext.currentTime
);
oscillator.start();
// Stop the oscillator after a short duration (adjust as needed)
setTimeout(() => {
oscillator.stop();
this.tone === sequence[sequence.length - 1]
? (this.tone = sequence[0])
: (this.tone = sequence[sequence.indexOf(this.tone) + 1]);
}, 100);
}
resetPlaySequenceOrder() {
this.tone = 310;
}
}
1.Create audioContext.oscillator.gainNode in constructor avoid any delay when you playsound
2.Oscillator.start only can play once,take care
3.Run my code on "Run code snippet" "full page" button will work fine,on current page something wrong happened!!!