Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

[SOLVED] My music player script plays two songs at once. Fix?

Asked by 5 years ago
Edited 5 years ago

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)

01local btn = script.Parent
02local db = true
03local val = script.Parent.Toggle
04local ss = game.SoundService
05local s1 = ss.Sound1
06local s2 = ss.Sound2
07local s3 = ss.Sound3
08local s4 = ss.Sound4
09local s5 = ss.Sound5
10 
11val.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)
View all 51 lines...

Please help if you know a solution, thanks!

2 answers

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

Try this:

01local btn = script.Parent
02local db = true
03local val = script.Parent.Toggle
04local ss = game.SoundService
05local s1 = ss.Sound1
06local s2 = ss.Sound2
07local s3 = ss.Sound3
08local s4 = ss.Sound4
09local s5 = ss.Sound5
10 
11val.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)
View all 52 lines...

So that wait(s..n.TimeLength) will let the infinite loop wait for the song to finish before choosing another song randomly.

Ad
Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

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--
02local btn = script.Parent
03local db = true --debounce
04local val = script.Parent.Toggle
05 
06--Music variables--
07local ss = game.SoundService
08local s1 = ss.Sound1
09local s2 = ss.Sound2
10local s3 = ss.Sound3
11local s4 = ss.Sound4
12local s5 = ss.Sound5
13 
14btn.MouseButton1Click:Connect(function()
15    if db == true then
View all 34 lines...

Music Player Script

01local ss = game.SoundService
02local s1 = ss.Sound1
03local s2 = ss.Sound2
04local s3 = ss.Sound3
05local s4 = ss.Sound4
06local s5 = ss.Sound5
07 
08while true do
09    local n = math.random(1,5)
10    if n == 1 then
11        s1:Play()
12        wait(0.1)
13        db = true
14        s1.Ended:Wait()
15    elseif n == 2 then
View all 36 lines...

Answer this question