I need a javascript that plays audio when the enemy is near you and it keeps looping until its a distance away from the player, then when the enemy is far away it stops looping.
Well an easy trick would be to just add an audio source to the enemy and play the sound in a loop. You would have to adjust the settings of the audio you are playing and make sure it is a 3d sound. This would make the audio increase as the camera approaches the enemy and decrease as it moves away. The only drawback to this is that multiple enemies close together would play the track multiple times.
Another option would be to use raycasting on from the middle of the camera extending to both sides. When the raycast detects the enemy’s layer, you could play the audio.
Why don’t you just calculate the distance to the enemies?
If there is at least 1 enemy under a certain distance you determine then you play your audio clip.