I want to improve my music player script. Right now, when a player presses a button, the music is toggle on/off. However, since the script waits for the sound to end, if the sound is paused, the script doesn't exit the "if" statement, meaning that if that sound ends after being toggled back on, it will play two sounds. (sorry if that's confusing, basically my script sometimes plays two songs at once)
01 | local btn = script.Parent |
02 | local db = true |
03 | local val = script.Parent.Toggle |
04 | local ss = game.SoundService |
05 | local s 1 = ss.Sound 1 |
06 | local s 2 = ss.Sound 2 |
07 | local s 3 = ss.Sound 3 |
08 | local s 4 = ss.Sound 4 |
09 | local s 5 = ss.Sound 5 |
10 |
11 | val.Changed:Connect( function () |
12 | if val.Value = = true then |
13 | btn.Text = "Music ON" |
14 | while true do |
15 | local n = math.random( 1 , 5 ) |
Please help if you know a solution, thanks!
Try this:
01 | local btn = script.Parent |
02 | local db = true |
03 | local val = script.Parent.Toggle |
04 | local ss = game.SoundService |
05 | local s 1 = ss.Sound 1 |
06 | local s 2 = ss.Sound 2 |
07 | local s 3 = ss.Sound 3 |
08 | local s 4 = ss.Sound 4 |
09 | local s 5 = ss.Sound 5 |
10 |
11 | val.Changed:Connect( function () |
12 | if val.Value = = true then |
13 | btn.Text = "Music ON" |
14 | while true do |
15 | local n = math.random( 1 , 5 ) |
So that wait(s..n.TimeLength) will let the infinite loop wait for the song to finish before choosing another song randomly.
Actually I've figured it out. Since a script is 'restarted' when it's disabled and then re-enabled, I can make a script just for playing the music and make another script for changing the button's text and enabling and disabling the music player script.
Disabler/Enabler Script
01 | --Main variables-- |
02 | local btn = script.Parent |
03 | local db = true --debounce |
04 | local val = script.Parent.Toggle |
05 |
06 | --Music variables-- |
07 | local ss = game.SoundService |
08 | local s 1 = ss.Sound 1 |
09 | local s 2 = ss.Sound 2 |
10 | local s 3 = ss.Sound 3 |
11 | local s 4 = ss.Sound 4 |
12 | local s 5 = ss.Sound 5 |
13 |
14 | btn.MouseButton 1 Click:Connect( function () |
15 | if db = = true then |
Music Player Script
01 | local ss = game.SoundService |
02 | local s 1 = ss.Sound 1 |
03 | local s 2 = ss.Sound 2 |
04 | local s 3 = ss.Sound 3 |
05 | local s 4 = ss.Sound 4 |
06 | local s 5 = ss.Sound 5 |
07 |
08 | while true do |
09 | local n = math.random( 1 , 5 ) |
10 | if n = = 1 then |
11 | s 1 :Play() |
12 | wait( 0.1 ) |
13 | db = true |
14 | s 1. Ended:Wait() |
15 | elseif n = = 2 then |