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

How do I get the sound to stop when I let go of the selected key?

Asked by 8 years ago
Edited 8 years ago

I have a script that plays a sound, among other things, when you press a key. What I want to know is to how you make the sound stop when you let go of the key? Did I mess up?

repeat wait() until game.Players.LocalPlayer

mouse = game.Players.LocalPlayer:GetMouse()

mouse.KeyDown:connect(function (key) -- Run function
    key = string.lower(key)
    if string.byte(key) == 48 then
        script.Parent.ImageTransparency = 0
      game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 95
    game.Workspace.Sound3:Play()
    end
end)

mouse.KeyUp:connect(function(key)

    key = string.lower(key)
    if string.byte(key) == 48 then
        script.Parent.ImageTransparency = 1
      game.Players.LocalPlayer.Character.Humanoid.Walkspeed = 40
    game.Workspace.Sound3:Stop()
    end
end)

*** Help me***

1
Don't use KeyDown or KeyUp. User#11440 120 — 8y

2 answers

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

This is my favorite way to do it, although it is not the only way.

I suggest using UserInputService and its InputBegan and InputEnded events. Also take a look at InputObjects and KeyCodes.

Basically, you want something (LocalScript) like this:

local userInputService = game:GetService("UserInputService")
local localPlayer = game.Players.LocalPlayer

local cloneSound = game.Workspace["Sound3"]:Clone()
cloneSound.Parent = localPlayer.Character

local function onInputBegan(input, gameProcessed)
    if input.UserInputType == Enum.UserInputType.Keyboard then
        local keyPressed = input.KeyCode
        if keyPressed == Enum.KeyCode.F then
            cloneSound:Play() -- Replace with "Resume()" if you want to play from where it left off last.
        end
    end
end

local function onInputEnded(input, gameProcessed)
    if input.UserInputType == Enum.UserInputType.Keyboard then
        local keyPressed = input.KeyCode
        if keyPressed == Enum.KeyCode.F then
            cloneSound:Stop() -- Replace with "Pause()" if you want to pause instead of stop.
        end
    end
end

UserInputService.InputBegan:connect(onInputBegan)
UserInputService.InputEnded:connect(onInputEnded)
Ad
Log in to vote
1
Answered by 8 years ago

Deprecated Events

Both the KeyDown and KeyUp events have been deprecated for getting keyboard input. The new recommendation is to use either the UserInputService or the ContextActionService for dealing with input (Other than mouse input, for which you should still use the events and properties from the Mouse object)

Answer this question