Magnetic switch loop

is it possible to achieve such a function?

Yes and we have been telling you over and over what you need to do.

One more time:-
You need to detect the change between the box being open and it being closed and use that to trigger the code that makes the sounds.
The sound will not continually play if you actually do this.