Running external programs with Python

Asked

Viewed 1,506 times

2

I would like to reduce the size of several Mp3 files in a directory with:

ffmpeg -i k.mp3 -acodec libmp3lame -ac 2 -ab 16k -ar 44100 k_.mp3

where K is the name of the Mp3 (k from 1 to 8):

Diretorio

I tried the following code:

    import subprocess

for x in range(1, 9):
    r = subprocess.call(["ffmpeg", " ffmpeg -i x.mp3 -acodec libmp3lame -ac 2 -ab 16k -ar 44100 x_.mp3"])

Then I would like to rename all the files like this:

1_mp3 vira    Sri Harinama - Aula 1
2_mp3 vira    Sri Harinama - Aula 2
3_mp3 vira    Sri Harinama - Aula 3
4_mp3 vira    Sri Harinama - Aula 4
5_mp3 vira    Sri Harinama - Aula 5

...
9_mp3 vira    Sri Harinama - Aula 9

Any suggestions?

1 answer

4


The subprocess.call can execute a command with arguments. For this you need to pass a list as parameter. The first item in this list is the name of the command to be executed. The other items are the arguments of this command.

You passed the string x.mp3 and x_.mp3 as input and output file name, respectively. These values will not be overwritten by the value x declared no. This can be solved, for example by using str.format to change the value of a string and run ffmpeg dynamically for all values of range(1, 9).

Try to run this way (untested code):

import subprocess

input_file_fmt = '{}.mp3'
output_file_fmt = 'Sri Harinama - Aula {}.mp3'

for x in range(1, 9):
    subprocess.call(['ffmpeg',
                     '-i',
                     input_file_fmt.format(x),
                     '-acodec',
                     'libmp3lame',
                     '-ac',
                     '2',
                     '-ab',
                     '16k',
                     '-ar',
                     '44100',
                     output_file_fmt.format(x)])

Line 3 defines the formatting of the input file name. Ex.: 1.mp3, 2.mp3, ...

Line 4 defines the formatting of the output file name. Ex.: Sri Harinama - Aula 1.mp3, Sri Harinama - Aula 2.mp3, ...

  • thanks. Once I test, I come back here to comment and mark as solved!

  • :I tried to run:http://imgur.com/a/PKLOU but the code did nothing (nor did it fail either).

  • Are you running in the same directory as the files to be processed? Place the python script in the same file directory or change the working directory using os.chdir.

  • Beginner doubt. If the files do not exist, you should not have an error message?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.