+ 1

(Web Audio API) Is it possible to start/stop the oscillator more than once?

https://code.sololearn.com/WeiGA1770Zy4/?ref=app The oscillator.stop() method seems to only mute the oscillator as it still runs in the background. Is there a way to fix the error when clicking again the start button?

31st Dec 2022, 1:25 PM
AlexFr
AlexFr - avatar
9 Answers
+ 3
Calviղ I think you are creating and stacking oscillators. push start more than once, only last one will stop. AlexFr I don't know JS but think hopefully this modified code is more rational. https://code.sololearn.com/W025Fb0XPNr3/?ref=app
31st Dec 2022, 11:51 PM
Tina
Tina - avatar
31st Dec 2022, 1:37 PM
PanicS
PanicS - avatar
+ 3
AlexFr That also works but the general rule is to free up whatever you've allocated so your code doesn't waste resources. when it gets big and runs a long time it'll have a huge negative impact on whole system and might fail too.
1st Jan 2023, 11:51 AM
Tina
Tina - avatar
31st Dec 2022, 1:51 PM
Calviղ
Calviղ - avatar
+ 1
Tina 🕊🇺🇦🇮🇷 You're right about the stacking issue. It was fine in my case cause I would just add btn-disabled in the start button but I guess is poor practice
1st Jan 2023, 10:42 AM
AlexFr
AlexFr - avatar
+ 1
AlexFr method is fine, since his program has prevented the button executed again, no resources is wasted. Tina 🕊🇺🇦🇮🇷 you're right, i should have added a control status there to prevent overlapping play method going on.
1st Jan 2023, 1:45 PM
Calviղ
Calviղ - avatar
+ 1
Calviղ Yes in this case stacking the nodes is not a problem but still, it's better not having the audio running unnecessarily in the background.
1st Jan 2023, 7:00 PM
AlexFr
AlexFr - avatar
+ 1
AlexFr AudioContext is fun. Late entry, trying to functionally create separate independent audio blocks. Memory leak is tricky. Starting, stopping, connecting and disconnecting multiple instances all add up to the confusion that leads orphan processes that's left running in the background. Oscillators can only be started once in every session. You have to do a check before calling the start method or you will get a warning if you start it more than once. To turn the sound on or off, use the connect and disconnect methods. To prevent sound still running when you close the oscillator, you should add a disconnect, then a stop and finally a close then remove in your close function. I also added delete ctx just to be sure. Make the close function as clean and thorough as possible. https://code.sololearn.com/WpBEjx7MtZ97/?ref=app
2nd Jan 2023, 3:56 PM
Bob_Li
Bob_Li - avatar
+ 1
Bob_Li What I am trying to do is much simpler as shown in Tina's and Calvin's code, 😅 but I will consider this for later. Thanks
3rd Jan 2023, 11:08 AM
AlexFr
AlexFr - avatar