How do I make a 'press M to mute music' script?

Hello, I’m a beginner developer and I want to make a script that if you press “M” on your keyboard then the audio thats playing in your game will be muted.

I’m stuck with a word in the script. What do I need to place on the question marks to make it work? (If there is anything else wrong with the script please say that too.)

Here is a picture of the script I have so far:

I hope someone can help me with this, thank you. :slightly_smiling_face:

1 Like

I suggest you make a gui with an on and off button because for mobile players, but depends on the game, but heres a tutorial! PRESS 'M' TO MUTE MUSIC!!! roblox studio - YouTube

Unfortunality, I cannot do that. The game is a second person shooting game. Aka, you cannot use a mouse arrow in the game. The game is obviously PC only, so I need to make keyboard functions. But thank you for your help!

You can use the UserInputService.InputBegan event and check if the player pressed M.

First thing, I BELIEVE LocalScripts don’t work in workspace. You can put the script in StarterPlayerScripts, or StarterGui.

Solution:

Once you have re-parented the script, there’s a little something called UserInputService. You can read about it here:

UserInputService has a… connection thing (idk what to call it) known as “InputBegan”. When a player presses something on their keyboard, it will call that… connection thing.

For example:

local userInputService = game:GetService("UserInputService")

userInputService.InputBegan:Connect(function(input)
      --[[ input variable is actually an instance, to get what they pressed, we need to type "input.KeyCode" --]]
     if input.KeyCode == Enum.KeyCode.M then -- if they press M key, then mute
           -- run the muting
     end
end)
1 Like

Put this code in a local script in starter player scripts.

local UIS = game:GetService("UserInputService")
local debounce = false
local music = game.Workspace:WaitForChild("Music")

UIS.InputBegan:Connect(function(input). --fires whenever they use keyboard
       if input.KeyCode = Enum.KeyCode.M and debounce == false then  --check if they pressed M
               debounce = true     
               if music.Volume == 0 then
                     music.Volume = 1 
              else
                    music.Volume = 0
              end
               wait(0.5)
               debounce = false
      end
end)
2 Likes
local uis = game:GetService('UserInputService')
local music = script.Sound -- create a sound instance inside the local script

toggleMusic = function()
    if music.Playing then
        music:Pause()
    else
        music:Resume()
    end
end

uis.InputBegan:Connect(function(input, isTyping)
    if isTyping then return end
    if input.KeyCode == Enum.KeyCode.M then
        toggleMusic()
    end
end)
1 Like

Thank you everyone, this helped a lot. Have a great day. :smiley: