Typing into Terminal works, AppleScript partially works

applescriptcommand lineterminal

What I am trying to achieve:

  1. Click a YouTube link in an app
  2. This URL is used by my youtube-dl script to download the video
  3. youtube-dl is configured to download the highest quality video and audio, then use ffmpeg to combine them into one file

What I have so far:

I use Finicky as my default browser. This gives me control over what browsers open certain links based on rules I write for it. The long and short of the tool is that it detects YouTube links, converts them from their usual form (e.g. https://www.youtube.com/watch?v=XxXxXxXXX_X) to the shortened, share-friendly form (e.g. https://youtu.be/XxXxXxXXX_X), then sends this to an AppleScript.

The AppleScript is saved as an app and is below.

#!/bin/zsh
on open location input
    do shell script "youtube-dl  " & input
end open location

This runs the shell script youtube-dl https://youtu.be/XxXxXxXXX_X. When I type this exact command into Terminal everything works perfectly: youtube-dl does it's thing, including doing something with ffmpeg to combine the downloaded files. However, when this AppleScript runs it's like ffmpeg isn't involved. I get a video file and an audio file.

I think my issue is in my AppleScript, but I am out of my depths with it. What can I do to make my AppleScript run things just like they run in Terminal?

Best Answer

What can I do to make my AppleScript run things just like they run in Terminal?

Well, you could tell the Terminal app to run your command:

tell application "Terminal" to do script "youtube-dl  " & input

But, I don't recommend this route, because it will actually open a Terminal window!

There are a whole host of differences between do shell script and typing commands into the Terminal. For starters, do shell script commands are run via sh, rather than the more advanced bash or zsh (And, your "#!/bin/zsh" shabang line at the top will have no effect in an Applescript!).

As to your actual problem, it sounds like youtube-dl can't find your copy of ffmpeg—probably because another difference between the Terminal app and do shell script is your PATH is set differently. Try specifying the location of your ffmpeg binary with youtube-dl's --ffmpeg-location flag.

If it helps to have a reference to look at, here is an Applescript I use to download videos from my web browser with youtube-dl. Note that I've been tweaking this for many years, so it has accumulated a lot of error checking, and code for compatibility with different browsers. Don't be intimidated! https://gist.github.com/Wowfunhappy/c2c8fc097a8b4f47430811fc1d0da041