Music Player Inefficient

Hello Everyone,

I’m trying to make a music player.

This is my current code:

local MusicFrame = script.Parent.Music
local IDBox = MusicFrame.IDBox
local PlayButton = MusicFrame.PlayButton

local Music = workspace.Music.Music

PlayButton.MouseButton1Click:Connect(function()
	Music.SoundId = "rbxassetid://"..IDBox.Text
	Music:Play()
end)

Script Info: the “Music” Variable is a sound object in workspace
IDBox is a Textbox Object.
PlayButton is a TextButton Object.

Well sure, this does work. So what’s the problem?

The problem is that I believe this is a very inefficient way of making a music player because if the player types any letters into the TextBox then it will error, preventing it from working, same if they input an ID that doesn’t exist.

I would suggest putting MarketplaceService:GetProductInfo() and put it in a pcall (as it already should be since it’s a web request) and this means the only error you must handle is if the requested asset ID is invalid. ProductInfo() will let you check if the asset ID is an audio and additonal information on it’s name, uploader, etc.

local inputBox = MusicFrame.IDBox

local previousText = ""
inputBox:GetPropertyChangedSignal("Text"):Connect(function()
   if string.match(inputBox.Text,"%D") then -- %D is any character besides a digit, so if it has anything but a digit it fires
      inputBox.Text = previousText
   else
      previousText = inputBox.Text
   end
end)

This way if a character is every typed it will undo it and keep the digits only.

This is a very useful formula, I use it all the time. Simple, efficient and short. It doesn’t fail, really good to use with any number only input. Works with characters only as well, visit the string patterns page

PS: This may not be 100% correct, but I remembered using string.match and working flawlessly. If anything visit this page for extra support with stirng.match and string patterns

But to check if an ID exists you still have to use getProductInfo, although making sure its an ID and not just characters before using getProductInfo will make your code more efficient as it doesnt need to wait for a server response

1 Like