AHK to auto run a Web Source Script from outside Mp3tag



c1d42315529de62ba4bd4a95d867666d

Revolut



Here's something I wrote to automatically run a script outside of Mp3tag, in my case foobar2000.

Any CLI will work so long as AHK is supported.

It'll ask the user to close once the saved file operation is finished. So all you'd have to do is go through the List of search results window and then ensure the adjust tag info is ok. Then a yes, no dialog where all you need to do is press enter to close Mp3tag.

So 3 baby steps :baby:

You need to change some stuff for this to suit your needs so read the header of the file carefully.

Just the CLI command needs changing in the latest release



If you've any questions just ask. Or if you have any improvements too, then please let me know.

Icon for anyone who may need it tag-with-web-source-scripts-in-mp3tag

Script in action

Code to save to the .ahk file

; #---------------------------------------------------------------------------------------------------------#
; # Tag with Web Source Scripts in Mp3tag.ahk written by stevehero
; #---------------------------------------------------------------------------------------------------------#
; # Version 0.1 beta -  2021.02.16 - First release.
; # Version 0.1a beta - 2021.02.17 - Improvements and bug fixes.
; # Version 0.1b beta - 2021.02.18 - Improvements.
; # Version 0.2a beta - 2021.02.23 - Rewrote entire thing to use functions and timers for the various window
; #                                  changes. This helps increase the speed of the script as there's no hard
; #                                  coded Wait commands in there. Also leaves it easier to edit.
; #                                - CTRL+ESC key will close Mp3tag at any time throughout.
; #                                - Splash screen and MsgBox are centered to the Mp3tag window.
; # Version 0.2b beta - 2022.01.22 - Tried to fix the problem with the script sticking (sometimes) after opening
; #                                  in Mp3tag. Works better but not foolproof.
; # Version 0.2c beta - 2024.03.09 - Correct fix for the problem with the script sticking after opening and not
; #                                  loading any files in Mp3tag and running the script.
; #---------------------------------------------------------------------------------------------------------#
; # You can buy me a beer or an EP on beatport
; # https://revolut.me/stephen147
; #---------------------------------------------------------------------------------------------------------#
; #
; #---------------------------------------------------------------------------------------------------------#
; # WHAT IT DOES WITH FOOBAR2000 OR ANY CLI:
; #---------------------------------------------------------------------------------------------------------#
; # when you use this it will fire the appropriate keyboard shortcut to use the
; # correct script.
; # As an example in Mp3tag to search by album artist and release the keyboard
; # shortcut is: Alt, S, S, R. so this will run that depending on the arguments
; # you give it.
; # See the section below 'SYNTAX'.
; #---------------------------------------------------------------------------------------------------------#
; # HOW TO SET-UP SETTING WITH FOO_RUN:
; #---------------------------------------------------------------------------------------------------------#
; # 1. First, download and install the plugin and AHK.
; #    https://www.foobar2000.org/components/view/foo_run
; #    https://www.autohotkey.com/
; # 2. Save all of this code to a file: Tag with Web Source Scripts in Mp3tag.ahk
; # 2. Go to: File>Preferences>Tools>Run Services.
; # 3. Click on Add.
; # 4. Give it a label such as:
; #    Tag with Beatport - Album Artist - Album
; # 5. In the Path field use:
; #    See the section below 'SYNTAX'.
; #---------------------------------------------------------------------------------------------------------#
; # HOW TO USE:
; #---------------------------------------------------------------------------------------------------------#
; # 1. Select a single track or the full album you want to tag in foobar2000. The
; #    way this works is it loads the directory of the track selected. Typically
; #    an album has its own directory anyway.
; # 2. Run it via the right-click context menu or alternatively you can add it to
; #    a toolbar.
; # 3. This will then run the script depending on the keyboard shortcuts used.
; #---------------------------------------------------------------------------------------------------------#
; # NOTE:
; #---------------------------------------------------------------------------------------------------------#
; # If you modify this make sure there's a keyboard shortcut to the script in
; # Mp3tag first otherwise it won't work.
; #---------------------------------------------------------------------------------------------------------#
; # SYNTAX:
; #---------------------------------------------------------------------------------------------------------#
; # Wrap any paths with " (Quotes).
; # "<AutoHotkey Path.exe>" "<Path to AHK Script>" "<Path of folder to process in Mp3tag>" "<Short cut keys>"
; # Here's my working example:
; # "W:\Apps '('Portable')'\AutoHotkey\AutoHotkeyU64.exe" "W:\Apps '('Portable')'\Music Apps\foobar2000\.autohotkey-routines\Tag with Web Source Scripts in Mp3tag.ahk" "%_path%" "{s}{s}{r}"
; #---------------------------------------------------------------------------------------------------------#; #---------------------------------------------------------------------------------------------------------#
; # MP3TAG THREAD:
; #---------------------------------------------------------------------------------------------------------#
; # https://community.mp3tag.de/t/ahk-to-auto-run-a-web-source-script-from-outside-mp3tag/52002
; #---------------------------------------------------------------------------------------------------------#

#SingleInstance,Force
SetTitleMatchMode,RegEx
#Persistent

arg = %1%
global keystopress
keystopress = %2%
global msgBoxTitle

; Open Mp3tag first
if WinExist("Mp3tag v.*") {
WinActivate
Run, "W:\Apps (Portable)\Music Apps\Mp3tag\Mp3tag.exe" "/fp:%arg%",,xPID
}
else
{
Run, "W:\Apps (Portable)\Music Apps\Mp3tag\Mp3tag.exe" "/fp:%arg%",,xPID
WinWaitActive ahk_exe Mp3tag.exe
}

; Set up the timers after first trying to open Mp3tag
SetTimer, CenterMsgBox, 10
SetTimer, CenterSplashScreen, 10
SetTimer, Close, 1500
SetTimer, IsReady, 1500
SetTimer, IsSaved, 500

SplashTextOff

^Esc::WinKill ahk_exe Mp3tag.exe

RunKeyboardShortcuts() {
  ; Select all the files and SendInput the Alt key to access the menu and run the web source script.
  Sleep, 500 ; Wait a small amount of time first.
  SendInput ^a
  Sleep, 500 ; Wait a small amount of time first.
  SendInput {ALT}
  ; Here are the keyboard shortcuts for the Mp3tag script. Change the CLI in your program to suit.
  SendInput %keystopress%
  ; Automatically accept the search box.
  SendInput {ENTER}
}
return

AskToCloseMp3tag() {
  msgBoxOptions := 4
  msgBoxOptions += 32
  msgBoxOptions += 4096
  msgBoxTitle = Close Mp3tag?
  msgBoxText = Do you want to close Mp3tag? (Press YES or NO)`n`nIMPORTANT`:`nYou will not be able to undo previous changes made.
  MsgBox, % msgBoxOptions, %msgBoxTitle% , %msgBoxText%
  IfMsgBox, Yes
  {
    if WinExist("Mp3tag v.*") {
      WinActivate
      WinKill ahk_exe Mp3tag.exe
    }
    Exit
  }
  IfMsgBox, No
  {
    Exit
  }
  Return
}

CenterSplashScreen:
IfWinExist, Please Wait`, Loading Files from...
{
  WinGetPos, , , msg_W, msg_H, Please Wait`, Loading Files from...
  SetTimer, CenterSplashScreen, Off
  WinMove, Please Wait`, Loading Files from..., , (mainUIW/2+mainUIX-(msg_W/2)), (80+mainUIH/2+mainUIY-(msg_H/2))
}
return

CenterMsgBox:
IfWinExist, Close Mp3tag?
{
  WinGetPos, , , msg_W, msg_H, Close Mp3tag?
  SetTimer, CenterMsgBox, Off
  WinMove, Close Mp3tag?, , (mainUIW/2+mainUIX-(msg_W/2)), (mainUIH/2+mainUIY-(msg_H/2))
}
return

IsReady:
WinWaitActive ahk_exe Mp3tag.exe
StatusBarGetText, RetrievedText, 1, ahk_exe Mp3tag.exe
If (RegExMatch(RetrievedText, ".*Ready.*")) {
  ; MsgBox, %RetrievedText% is found.
  SetTimer, IsReady, Off
  RunKeyboardShortcuts()
}
Return

; Here's where the script will check if the files have been saved and give the user the option to close the Mp3tag.
; The default button here is Yes, so you can just hit enter.
IsSaved:
WinWaitActive ahk_exe Mp3tag.exe
StatusBarGetText, RetrievedText, 1, ahk_exe Mp3tag.exe
If (RegExMatch(RetrievedText, ".*Saved tag.*")) {
  ; MsgBox, %RetrievedText% is found.
  SetTimer, IsSaved, Off
  Sleep 50 ; Give it a little more time.
  AskToCloseMp3tag()
}
Return

; Close the ahk script when Mp3tag is closed.
Close:
IfWinNotExist ahk_exe Mp3tag.exe
ExitApp
; Exit
Return

;; End code
1 Like

Doing some AHK myself, I would recommend ( in ahk doc as well) using sendinput instead of send, especially when multi-windowing.

It works as is. Here's an SO thread that says it should only be used if Send doesn't work.

Update the script to fix the loading issue

; # Version 0.2c beta - 2024.03.09 - Correct fix for the problem with the script sticking after opening and not
; #                                  loading any files in Mp3tag and running the script.

Updated to AHK v2

; AHK v2 COMPATIBLE

; ---------------------------------------------------------------------------------------------------------
;  Tag with Web Source Scripts in Mp3tag.ahk written by stevehero
; ---------------------------------------------------------------------------------------------------------
;
;  Version 0.1 beta -  2021.02.16 - First release.
;  Version 0.1a beta - 2021.02.17 - Improvements and bug fixes.
;  Version 0.1b beta - 2021.02.18 - Improvements.
;  Version 0.2a beta - 2021.02.23 - Rewrote entire thing to use functions and timers for the various window
;                                   changes. This helps increase the speed of the script as there's no hard
;                                   coded Wait commands in there. Also leaves it easier to edit.
;                                 - CTRL+ESC key will close Mp3tag at any time throughout.
;                                 - Splash screen and MsgBox are centered to the Mp3tag window.
;  Version 0.2b beta - 2022.01.22 - Tried to fix the problem with the script sticking (sometimes) after opening
;                                   in Mp3tag. Works better but not foolproof.
;  Version 0.2c beta - 2024.03.09 - Correct fix for the problem with the script sticking after opening and not
;                                   loading any files in Mp3tag and running the script.
;  Version 1.0       - 2025.07.06 - Rewrote code for AHK v2.
;                                 - Added a timer to the message box at the end to automatically close Mp3tag.
;                                   Which can be changed with the MsgBoxDelaySecs variable below.
;                                   The default is set to 5 seconds.
;                                 - Changed Send to SendInput.
;
; ---------------------------------------------------------------------------------------------------------
;
;  You can buy me a beer or an EP on Beatport
;  https://revolut.me/stephen147
;
; ---------------------------------------------------------------------------------------------------------
;  WHAT IT DOES WITH FOOBAR2000 OR ANY CLI:
; ---------------------------------------------------------------------------------------------------------
;
;  - When you use this it will fire the appropriate keyboard shortcut to use the correct script.
;  - As an example in Mp3tag to search by album artist and release the keyboard shortcut is:
;    Alt, S, S, R. so this will run that depending on the arguments you give it.
;  - See the section below 'SYNTAX'.
;
; ---------------------------------------------------------------------------------------------------------
;  HOW TO SET-UP SETTING WITH FOO_RUN:
; ---------------------------------------------------------------------------------------------------------
;
;  1. First, download and install the plugin and AHK.
;     https://www.foobar2000.org/components/view/foo_run
;     https://www.autohotkey.com/
;  2. Save all of this code to a file: Tag with Web Source Scripts in Mp3tag.ahk
;  2. Go to: File>Preferences>Tools>Run Services.
;  3. Click on Add.
;  4. Give it a label such as:
;     Tag with Beatport - Album Artist - Album
;  5. In the Path field use:
;     See the section below 'SYNTAX'.
;
; ---------------------------------------------------------------------------------------------------------
;  HOW TO USE:
; ---------------------------------------------------------------------------------------------------------
;
;  1. Select a single track or the full album you want to tag in foobar2000. The
;     way this works is it loads the directory of the track selected. Typically
;     an album has its own directory anyway.
;  2. Run it via the right-click context menu or alternatively you can add it to
;     a toolbar.
;  3. This will then run the script depending on the keyboard shortcuts used.
;
; ---------------------------------------------------------------------------------------------------------
;  NOTE:
; ---------------------------------------------------------------------------------------------------------
;
;  If you modify this make sure there's a keyboard shortcut to the script in
;  Mp3tag first otherwise it won't work.
;
; ---------------------------------------------------------------------------------------------------------
;  SYNTAX:
; ---------------------------------------------------------------------------------------------------------
;
;  Wrap any paths with " (Quotes).
;  "<AutoHotkey Path.exe>" "<Path to AHK Script>" "<Path of folder to process in Mp3tag>" "<Short cut keys>"
;  Here's my working example:
;  "C:\Program Files\AutoHotkey\v2\AutoHotkey64.exe" "W:\Apps '('Portable')'\Music Apps\foobar2000\.autohotkey-routines\Tag with Web Source Scripts in Mp3tag.ahk" "%_path%" "{s}{s}{r}"
;
; ---------------------------------------------------------------------------------------------------------
;  MP3TAG THREAD:
; ---------------------------------------------------------------------------------------------------------
;
;  https://community.mp3tag.de/t/ahk-to-auto-run-a-web-source-script-from-outside-mp3tag/52002
;
; ---------------------------------------------------------------------------------------------------------

#SingleInstance Force
Persistent ; Keep the script running in the background for timers
SetTitleMatchMode "RegEx"

; ARGUMENTS, CHECK IF THE CORRECT NO. OF ARGUMENTS ARE SENT TO THIS SCRIPT
if A_Args.Length < 2 {
  MsgBox "Usage:`nScript.ahk <folder path> <shortcut keys>`n`nYou passed " A_Args.Length " argument(s)."
  ExitApp
}
arg := A_Args[1]
global ShortcutKeys := A_Args[2]

; GLOBALS
global Mp3tagHwnd := "ahk_exe Mp3tag.exe"
global Mp3tagName := "Mp3tag"
global Mp3tagPath := "W:\Apps (Portable)\Music Apps\Mp3tag\Mp3tag.exe"
global MsgBoxDelaySecs := 5
global MsgBoxHwnd := 0 ; To store the HWND of the MsgBox
global MsgBoxMsg1 := "Do you want to close " Mp3tagName "? (Press YES or NO)`n`nIMPORTANT:`n - You will not be able to undo previous changes made.`n - This message box and " Mp3tagName " will close in "
global MsgBoxMsg2 := " seconds."
global MsgBoxMsgFull := MsgBoxMsg1 . MsgBoxDelaySecs MsgBoxMsg2
global msgBoxTitle := "Close " Mp3tagName "?"

; TIMERS
SetTimer Mp3tagsSaved, 500
SetTimer TimerFnCenterSplashScreen, 10

; RUN MP3TAG WITH THE ARGUMENTS IF ALREADY OPENED OR NOT
if WinExist(Mp3tagHwnd) {
  WinActivate
  runArgs := '"/fp:' arg '"'
  Run('"' Mp3tagPath '" ' runArgs, , , &xPID)
  WaitRunKeyboardShortcuts()
} else {
  runArgs := '"/fp:' arg '"'
  Run('"' Mp3tagPath '" ' runArgs, , , &xPID)
  WaitRunKeyboardShortcuts()
}

; FUNCTION: to wait and then run the keyboard shortcuts
WaitRunKeyboardShortcuts() {
  ; Wait until Mp3tag window appears
  while !WinExist("Mp3tag v.*") {
    Sleep 100
  }
  ; Wait until Mp3tag shows "Ready" in the status bar
  Loop 20 {  ; Try for 10 seconds (20 x 500ms)
    text := ""
    try text := StatusBarGetText(1, Mp3tagHwnd)
    if InStr(text, "Ready") {
      ; MsgBox "Mp3tag is ready..."
      Sleep 500
      SendInput "^a"
      Sleep(500)
      SendInput "{Alt}"
      SendInput(ShortcutKeys)
      SendInput("{Enter}")
      break
    }
    Sleep 500
  }
}

; FUNCTION: check if the tags have been saved after the tag info panel is closed
Mp3tagsSaved() {
  if WinActive(Mp3tagHwnd) {
    text := ""
    try text := StatusBarGetText(1, Mp3tagHwnd)
    catch {
      return
    }
    if RegExMatch(text, ".*Saved tag.*") {
      SetTimer(Mp3tagsSaved, 0) ; Stop the timer
      Sleep 300
      ; Show the MsgBox on the main thread by calling via a timer with a slight delay
      SetTimer Mp3tagAskToClose, -100  ; Negative means run once after 100 ms
    }
  }
}

; FUNCTION: show message box to ask to close mp3tag.
Mp3tagAskToClose() {
  ; This timer will update the MsgBox's text. It will be started *before* the blocking MsgBox
  ; to ensure it can immediately begin trying to find and update the MsgBox once it appears.
  SetTimer(TimerFnMsgBoxCountdownUpdate, 1000) ; Call every 1 second
  SetTimer(TimerFnMsgBoxCenter, 1)  ; fires once after 10ms
  ; Show the message box
  MsgBoxResult := MsgBox(MsgBoxMsgFull, MsgBoxTitle, "YesNo Icon! 4096 T" MsgBoxDelaySecs)
  ; Stop the MsgBox timers as the MsgBox is gone
  SetTimer(TimerFnMsgBoxCountdownUpdate, 0)
  SetTimer(TimerFnMsgBoxCenter, 0)
  ; Depending on what was or wasn't pressed, do stuff
  if (MsgBoxResult = "timeout") {
    ; MsgBox("Time ran out. MsgBox closed automatically.")
    if WinExist(Mp3tagHwnd) {
      WinKill(Mp3tagHwnd)
    }
    TimersStopAll()
    ExitApp
  }
  If (MsgBoxResult = "Yes") {
    if WinExist(Mp3tagHwnd) {
      WinKill(Mp3tagHwnd)
    }
    TimersStopAll()
    ExitApp
  } else if (MsgBoxResult = "No") {
    TimersStopAll()
    ExitApp ; Exit the script
  }
}

;;
;; TIMER FUNCTIONS
;;

; TIMER FUNCTION, to update the MsgBox text
TimerFnMsgBoxCountdownUpdate() {
  global MsgBoxDelaySecs, MsgBoxHwnd
  ; Decrement seconds for the next display
  MsgBoxDelaySecs--
  if (MsgBoxDelaySecs <= 0) {
    global MsgBoxMsgFull := "Closing " Mp3tagName " and program..."
  } else {
    plural := (MsgBoxDelaySecs = 1 ? " second." : " seconds.")
    global MsgBoxMsgFull := MsgBoxMsg1 . MsgBoxDelaySecs . plural
  }
  MsgBoxHwnd := WinExist(MsgBoxTitle)
  if (MsgBoxHwnd) {
    ; Check to see if the control is Static1 or Static2 as the message box can be
    ; different if there's an icon or not
    for n, ctrl in WinGetControls("ahk_id " MsgBoxHwnd) {
      if InStr(ctrl, "Static") {
        text := ControlGetText(ctrl, "ahk_id " MsgBoxHwnd)
        if InStr(text, MsgBoxMsg1) || text = "Closing..." {
          MsgBoxControl := ctrl
          break
        }
      }
    }
    ControlSetText(MsgBoxMsgFull, MsgBoxControl, "ahk_id " MsgBoxHwnd)
    if (MsgBoxDelaySecs <= 0) {
      SetTimer(TimerFnMsgBoxCenter, 0)
      SetTimer(TimerFnMsgBoxCountdownUpdate, 0)
    }
  } else {
    ; If the MsgBox window no longer exists (e.g., user clicked OK/Cancel, or it was closed by timer already),
    ; stop this timer to avoid errors.
    SetTimer(TimerFnMsgBoxCenter, 0)
    SetTimer(TimerFnMsgBoxCountdownUpdate, 0)
    if WinExist(MsgBoxHwnd)
      WinClose("ahk_id " MsgBoxHwnd) ; Close the MsgBox when time runs out. Not needed if TX is used in the message box
  }
}

; TIMER FUNCTION, to center the splash screen
TimerFnCenterSplashScreen() {
  hwnd := WinExist("Please Wait, Loading Files from...")
  if hwnd {
    WinGetPos(&msgX, &msgY, &msgW, &msgH, hwnd)
    SetTimer(TimerFnCenterSplashScreen, 0)
    WinMove(hwnd, , (A_ScreenWidth // 2 - msgW // 2), (A_ScreenHeight // 2 - msgH // 2))
    WinActivate(Mp3tagHwnd)
  }
}

; TIMER FUNCTION, to center the MsgBox to the center of the Mp3tagHwnd
TimerFnMsgBoxCenter() {
  global MsgBoxTitle, Mp3tagHwnd
  MsgBoxHwnd := WinExist(MsgBoxTitle . " ahk_class #32770")
  if !MsgBoxHwnd
    return  ; MsgBox not shown yet
  ; Now we have the MsgBox hwnd, move it
  if (WinExist("ahk_id " Mp3tagHwnd)) {
    WinGetPos(&tx, &ty, &tw, &th, "ahk_id " Mp3tagHwnd)
    WinGetPos(&mx, &my, &mw, &mh, "ahk_id " MsgBoxHwnd)
    newX := tx + (tw // 2) - (mw // 2)
    newY := ty + (th // 2) - (mh // 2)
    WinMove newX, newY, , , MsgBoxHwnd
    SetTimer(TimerFnMsgBoxCenter, 0)  ; stop the timer
  }
}

; FUNCTION: to stop all the timers
TimersStopAll() {
  SetTimer(Mp3tagsSaved, 0)
  SetTimer(TimerFnCenterSplashScreen, 0)
  SetTimer(TimerFnMsgBoxCenter, 0)
  SetTimer(TimerFnMsgBoxCountdownUpdate, 0)
}

; KEYBOARD SHORTCUT, to close Mp3tag on Escape key
^Esc:: {
  WinKill Mp3tagHwnd
}