Search code examples
pythonffmpegyoutube-dlos.systemanaconda3

facing problem in downloading the audio data of a trimmed youtube video using youtube-dl and ffmpeg libraries


I'm trying to download the audio content of a trimmed YouTube video using youtube-dl (v2021.12.17) and FFmpeg (v4.2.2) libraries in python, on Windows 10 PC. I am able to download the audio data when the command is executed on the Pycharm terminal, but not able to download the same content when using os.system() command.

For example, I'm able to download the data when I execute

"ffmpeg -ss 30 -t 10 -i $(youtube-dl -f best -g https://www.youtube.com/watch?v=3NGZcpAZcl0) -- output1.wav"

command on the Pycharm terminal.

But, i'm getting an error, when I try to execute the same in the Editor window as shown below,

os.system('ffmpeg -ss 30 -t 10 -i $(youtube-dl -f best -g https://www.youtube.com/watch?v=3NGZcpAZcl0) -- output1.wav')

error: $(youtube-dl: No such file or directory

I also tried enclosing the $() link in quotes and then executed it. But, after doing this, I am getting a different error as shown below

os.system('ffmpeg -ss 30 -t 10 -i "$(youtube-dl -f best -g https://www.youtube.com/watch?v=3NGZcpAZcl0)" -- output1.wav')

error: $(youtube-dl -f best -g https://www.youtube.com/watch?v=3NGZcpAZcl0): Invalid argument

So, can any of you help me in resolving this error?


Solution

  • It doesn't work because your command is actually a shell script inserting a string from another system call by $(...). Python's os.system() can run only one shell command at a time (based on observation).

    What does this mean? You need to run youtube-dl and ffmpeg commands separately with subprocess:

    import subprocess as sp
    
    # run youtube-dl and capture its output as a string
    results = sp.run(['youtube-dl','-f','best','-g',
                      'https://www.youtube.com/watch?v=3NGZcpAZcl0'],
                     stdout=sp.PIPE,universal_newlines=True)
    url = results.stdout
    
    # run ffmpeg
    sp.run(['ffmpeg','-ss','30','-t','10','-i', url, 'output1.wav')