Sound plays when player presses a key

Hey!
Thank you for noticing and reading this.

I am trying to get a sound to play when the player presses a key e.g. ‘K’ or maybe ‘J’.
I have been trying a lot but I still cannot get it to work. (I am not much of a scripter)

Here is the script so far:
image

It would be greatly appreciated if you could help me.

Thank you.

Put the sound in the PlayerGui.

1 Like

I tried this, it doesn’t work.

You forgot to make the function fire
something like this

onKeyPress()

1 Like

He did that on line 7

game:GetService("UserInputService").InputBegan:Connect(onKeyPress)
1 Like

Also, try placing the Sound in SoundService instead? If that doesn’t work could you check if the Volume is at 0 or add print statements?

1 Like

Is it a script or a local script?

Script
I want everyone to hear it.

Only the client can detect input from the player. The server can’t. Make it a local script. Also shove the script into starterplayer > starterplayerscripts. If you want everyone to hear it then put the sound in like workspace and then play it on the server using a remote event / function if you need so everyone can hear it.

1 Like

This is unrelated to your issue, but you should use :Connect() instead of :connect() as the latter is deprecated.

1 Like

You can only detect keys with LocalScripts, you should detect the press and send a remote to the server, then play for everyone.

1 Like

Thank you very much, it works now.

Ahh my bad
in that case maybe he should use the API
a bit more

1 Like

Use RemoteEvents if you want to play the sound from the client to the server, and have the Sound inside the workspace to play it so that everyone can hear it, I’ll give an example:

--Client
local Event = game.ReplicatedStorage:WaitForChild("RemoteEvent")
local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(Key, GameDetect)
    if not GameDetect then return end --This will detect any non-ingame Inputs
   
     if Key.KeyCode == Enum.KeyCode.K then
        Event:FireServer()
    end
end)

--Server
local Event = game.ReplicatedStorage:WaitForChild("RemoteEvent")
local Sound = workspace.Sound

Event.OnServerEvent:Connect(function()
    Sound:Play()
end)
2 Likes

Thanks a lot for this. It really helps.

1 Like

Also, the server side script should be in server script service right?

Preferably yes, since it is good practice to know where to keep your scripts after all :slightly_smiling_face: Just keep in mind this:

  • LocalScripts will only work client sided in these 5 categories:

    • StarterPack
    • StarterGui
    • StarterPlayer/Character Scripts
    • ReplicatedFirst
    • (There was 1 more that I forgot gosh darn it)
  • While Server Scripts mostly work anywhere, but they don’t have access to the Local Player

3 Likes

Thanks, I’ve been getting confused over this in the past.

Yeah I understand :sweat_smile: It took me a week to figure out that, so don’t you worry about it everyone struggles

2 Likes