Search code examples
stringvariablesapplescripttruncateautomator

Working with Automator "Run Applescript" variables


Request assistance with truncating/trimming a string in an automator action used to create text-to-speech audio files from a text selection ranging from 30 or so characters to 800+, which is too long for a file name.

In short, I am trying to truncate a string to 30 characters and pass that to the "Text to Audio File" action as the file name.

Basic workflow is:

Select text Initiate following Automator Action via Services Menu

  1. "Set Value of Variable" to input (e.g. selected text) and define as TextToSpeech
  2. "Set Value of Variable" to input (e.g. selected text) and define as FileName
  3. "Get Value of Variable" FileName
  4. "Run AppleScript"

    on run {input, parameters}
        set theResult to input as string
        set finalResult to input as string
        set txtLength to (length of theResult)
        if txtLength > 30 then
            set finalResult to (characters 1 thru 30 of theResult) as string
        end if
        return finalResult
    end run
    
  5. "Set Value of Variable" input (e.g. selected text) and define as FileName

  6. "Get Value of Variable" TextToSpeech
  7. "Text to Audio File" with Save As: set to "FileName"
  8. "Encode to MPEG Audio"

Any assistance/suggestions is greatly appreciated!

Regards,

Zephyr


Solution

  • In general you pass from the applescript to the next action whatever it needs using the "return" command at the end of the code. In your case though the automator action "Text to Audio File" doesn't accept a fileName variable so if you want that much control you need another method. Luckily that automator action can be replaced easily in the applescript code with a simple "say" command.

    So create your automator service and receive the selected text. Then add an applescript action and use the following as the code. Then add an "Encode to MPEG audio" action.

    For the applescript code just modify the voiceName and saveFolder variables with values of your choosing. The saveFolder path must end with a colon (:). Note that I use 26 instead of 30 because we add ".aif" to the end of the filename... to get a total of 30 characters.

    on run {input, parameters}
        set voiceName to "Jill"
        set saveFolder to path to desktop as text
    
        set selectedText to item 1 of input
        if (length of selectedText) > 26 then
            set fileName to text 1 thru 26 of selectedText
        else
            set fileName to selectedText
        end if
        set fileName to fileName & ".aif"
        set filePath to saveFolder & fileName
    
        say selectedText using voiceName saving to file filePath
    
        return {POSIX path of filePath}
    end run
    

    If you need to determine your saveFolder use this to get the path. Run this code and copy/paste the result into the saveFolder variable above.

    (choose folder) as text