Executing external programs with Python

1

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 Mp3 (k from 1 to 8):

Itriedthefollowingcode:

importsubprocessforxinrange(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 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?

    
asked by anonymous 14.05.2017 / 00:43

1 answer

3

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 execute. The remaining items are the arguments for this command.

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

Try to run this way (code not tested):

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 , ...

    
14.05.2017 / 22:04