Repeat resaving audio files using QuickTime Player

I have a folder full of AAC audio files that were encoded wrong. Opening and resaving them using QuickTime Player is an effective way to fix them, however QuickTime Player does not permit replacing the files in place. Therefore, I’m designing an AppleScript to repeat the processing of the files. So far, this is what I have:


set inputFolder to "path:to:folder:"
tell application "Finder" to set audioFiles to files of entire contents of folder inputFolder
repeat with i in audioFiles
	set oneFile to i as alias
	tell application "QuickTime Player"
		activate
		open oneFile
		tell application "System Events"
			delay 2
			keystroke "s" using command down
			delay 2
			-- right arrow key
			key code 124
			-- delete key
			key code 51
			key code 51
			-- return key
			key code 36
			delay 2
			keystroke "w" using command down
		end tell
	end tell
end repeat

First, I’ve renamed all the files with " 1" at the end of the name. The idea is to open each file, invoke the Save command, go to the end of the file name, delete the last two characters, press Return to save, and then close the file and move on to the next.

The script is working fine for the first file but when it gets to the second, it fails to press the right arrow and ends up deleting the whole file name, stopping the save process in its tracks.

I’m confident that I’m making this more complicated than it needs to be and would appreciate some insight toward simplification.

[For what it’s worth, running macOS 10.13.6]

Hmm. Quicktime Player 10 isn’t as scriptable as it likes to pretend. :confused:

This works for me as a GUI Scripting solution.

-- This script uses GUI Scripting, which must be enabled on the machine running it.

set inputFolder to "path:to:folder:"
tell application "Finder" to set audioFiles to files of entire contents of folder inputFolder as alias list

tell application "QuickTime Player" to activate

repeat with oneFile in audioFiles
	-- Open the document and get its name.
	tell application "QuickTime Player" to set currentName to name of (open oneFile)
	
	tell application "System Events"
		tell application process "QuickTime Player"
			set frontmost to true
			-- Use a keystroke to invoke the "Save…" dialog and wait for it to appear.
			keystroke "s" using command down
			repeat until (sheet 1 of window 1 exists)
				delay 0.2
			end repeat
			-- Type the alternative name directly into the selection in the "Export As:" field, followed by a return to click the "OK" button.
			-- It's assumed here that each current name ends with "1.aac"
			keystroke (text 1 thru -6 of currentName) & return
			-- Wait for the dialog to clear.
			repeat while (sheet 1 of window 1 exists)
				delay 0.2
			end repeat
		end tell
	end tell
	
	-- Close the document.
	tell application "QuickTime Player" to close document 1
end repeat