Strap yourself in, because this is gonna be a long reply
Check that the sound is not set to looped. Apart from that, unless there’s something else controlling sound, it shouldn’t play over and over.
Code Issues
Your code has a few issues.
-
Playing sound using properties: You should always use :play
and :pause
when playing sound, instead of using the properties. Granted, they do the same thing, but the methods are better. Change the lines which set the “playing” property of the current sound to use :play and :pause
-
You don’t use the random variable in your code: The variable you use to select the random song is never used. You need it to be in the same script. To use it, you are going to need to shift around your codebase. As the changes required are quite large, I’ll put them underneath in their own section.
-
Incorrect script type: The script inside the mute button needs to be a localscript.
Fixing your code
I’m assuming you want to have a different song picked and played after the one selected is done. I’ll add that in for you.
I won’t post complete code, because then you won’t learn anything. However, I will give you steps to completion.
Before you start, please read the articles on audio playback on the Developer Hub. There are some simple things you overlooked which you should really learn before trying this again.
Step 1
Rename each sound in the SoundService from 1, to how many there are. This will be vital later on.
So, if there are 10 sounds, they should be named from 1 to 10.
Step 2
Move your code from your randomising script into the mute script. They are needed there. Ensure that they come after the sound variable.
Step 3
Next to the sound variable, add a new one called “CurrentSound”. We’re going to store the sound to play here. Set it to nil.
Step 4
Change the sound played in the “script.Parent.MouseButton1Click” event so that it is the CurrentSound variable we just made. This makes it so that we mute the sound which is currently playing, not just a single sound which may not be playing.
Step 5
Enclose your randomisation script in an infinite loop, but change a single thing. On the line which sets the random song variable:
local RandomSound = Sounds[math.random(1, #Sounds)]
Change it so that it sets CurrentSound instead. Be sure to remove the local keyword!
FYI, and infinite loop looks like this:
while true do
-- Do stuff here
end
Step 6
Near the end of the infinite loop, add the following code:
CurrentSound.Ended:Wait()
This makes sure we wait until the song ended, before we select a new one.
Step 7
Move the part where you connect events to after you declare the “CurrentSound” variable, or they will never run due to the loop.
Make all of these changes and post the script you now have so that I can check it over. Also, try it out. Tell me any errors you get. I think this should work, but my instructions may have some errors on my part.
That’s not needed. I do this kind of thing for fun. Don’t worry about rewarding me.