05-16-26

Loop Audio Sample Trigger Script

Create a loop sampler using Lua and hardware input. This Rebind script allows you to trigger and control the playback of audio samples with a mouse click, offering both hold and toggle modes.

rebindlua scriptloopaudiosampletriggerscript

Question

I want to trigger an auto-loop playback with a mouse click.

Rebind AI

lua
-- rebind: name=Loop Sampler Trigger

local cfg = UI.Schema({
    sample = UI.Text("sample.wav", { 
        label = "Sample File", 
        placeholder = "filename.wav",
        maxLength = 100 
    }),
    volume = UI.Slider(0.8, { min = 0, max = 1, label = "Volume" }),
    loop_delay = UI.Slider(100, { min = 0, max = 1000, suffix = "ms", label = "Loop Delay" }),
    trigger = UI.Keybind("Mouse1", { label = "Trigger Button" }),
    mode = UI.Select("Hold", { "Hold", "Toggle" }, { label = "Mode" }),
})

local playing = false
local task = nil

function OnStart()
    if not File.Exists(cfg.sample) then
        Log.Warn("Sample file not found: " .. cfg.sample)
    end
end

function OnDown(key)
    if key ~= cfg.trigger then return true end
    
    if cfg.mode == "Hold" then
        task = Run(function()
            while Input.IsDown(cfg.trigger) do
                if File.Exists(cfg.sample) then
                    Audio.Play(cfg.sample, { volume = cfg.volume })
                    Sleep(cfg.loop_delay)
                end
            end
        end)
        return false
    elseif cfg.mode == "Toggle" then
        playing = not playing
        if playing then
            task = Run(function()
                while playing do
                    if File.Exists(cfg.sample) then
                        Audio.Play(cfg.sample, { volume = cfg.volume })
                        Sleep(cfg.loop_delay)
                    end
                end
            end)
            UI.Notify("Looping", "info")
        else
            if task and task:IsRunning() then
                task:Cancel()
            end
            Audio.StopAll()
            UI.Notify("Stopped", "info")
        end
        return false
    end
    
    return true
end

function OnStop()
    if task and task:IsRunning() then
        task:Cancel()
    end
    Audio.StopAll()
end

function OnBlur()
    if task and task:IsRunning() then
        task:Cancel()
    end
    Audio.StopAll()
    playing = false
end

How it works:

  • Hold mode: While you hold down the trigger button (default Mouse1), the sample loops continuously with a delay between plays.
  • Toggle mode: Click once to start looping, click again to stop.
  • Sample file: Place your WAV/MP3 file in your script's directory (e.g., sample.wav) and set the filename in the UI.
  • Loop delay: Control spacing between sample repeats (0 = no delay, back-to-back plays).
  • Volume: Adjust playback volume.

Put your audio file in the same folder as your script, then update the "Sample File" setting in the UI to match the filename.

Learn more