How to make a sound play at night and morning

Hello everyone. Im having trouble getting my code to work. I am trying to make the crickets sound play at night and the morning sounds play in the morning but when I join the game the crickets are automatically playing and don’t stop ever also when it reaches the specified morning time the morning sounds don’t start all I hear is the crickets.

here is my code:

local cricketsSound = workspace.Crickets
local morningSound = workspace.MorningSounds
local cricketsPlaying = false
local morningPlaying = false
local cricketsStartHour = 20 -- start hour for crickets
local cricketsEndHour = 5 -- end hour for crickets (next day)
local morningStartHour = 5 -- start hour for morning sounds
local morningEndHour = 8 -- end hour for morning sounds

while true do
	local time = os.date("*t", os.time())

	if time.hour >= cricketsStartHour or time.hour < cricketsEndHour then
		if not cricketsPlaying then
			cricketsSound:Play()
			morningSound:Stop()
			cricketsPlaying = true
			morningPlaying = false
		end
	elseif time.hour >= morningStartHour and time.hour < morningEndHour then
		if not morningPlaying then
			morningSound:Play()
			cricketsSound:Stop()
			morningPlaying = true
			cricketsPlaying = false
		end
	else
		cricketsSound:Stop()
		morningSound:Stop()
		cricketsPlaying = false
		morningPlaying = false
	end

	wait(60) -- wait for 1 minute before checking again
end

Can anyone help with this?

You are using real world time. If you want it to use the game clock you need to use the LightingService and something like:

Lighting:GetMinutesAfterMidnight()

Real world time moves very slow :slight_smile:

1 Like

A couple of things:

  • as @quakage suggested, use game time, not a real time clock.
  • You probably could check every 5 or 10 seconds inside the while true do loop using task.wait(5) because game clock time is usually set quicker than real world time by you. If an hour game time passes in 10 minutes real time then waiting 60 seconds could put you 6 ‘minutes’ behind in game time. Also, wait() is being deprecated by the more efficient task.wait().

Thank you this fixed my problem

Thank you this also helped and it’s now fixed

No worries!
Please mark @quakage’s post as the Solution so other people don’t keep commenting, or if someone has a similar problem and Searches they will see your post as solved.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.