1

I am trying to extract a certain audio segment from an entire audio file using ffmpy, which I haven't really worked with before. So far, I have looked into extracting a certain time range, which suggests to use a command like this:

ffmpeg -ss 00:01:00 -i input.mp3 -to 00:02:00 -c copy output.mp3

In my case, I am trying to write a Python script to do this over multiple audio files. Since I am reading from a csv and all that, I am storing important information in variables. However, being a first time user of ffmpy and ffmpeg I'm really not sure how I'm supposed to do that.

Below is the code that I have so far (including what I attempted to do to so far to extract the audio bits):

for line in reader:
        # Get access to the stored file as found in the audio_files dir
        print(line)
        folder_name = line[1].split("/")[len(line[1].split("/")) - 2]
        file_name = line[1].split("/")[len(line[1].split("/")) - 1]

        
        audio_file_path = "./audio_files/" + folder_name + "/" + file_name.split(".")[0] + ".mp3"
        print(audio_file_path)

        start_time = line[2]
        end_time = line[3]

        # Use ffmpy/ffmpeg to extract the audio bits
        ff = FFmpeg(inputs={file_name + ".mp3": "None"}, outputs={file_name + "_truncated.mp3": "None"})
        ff.cmd = 'ffmpeg -i "' + audio_file_path + '" -ss ' + start_time + ' -to ' + end_time + ' -async 1 ' + '"./audio_files/' + folder_name + '/' + file_name.split(".")[0] + '_cut.mp3"'
        print(ff.cmd)
        ff.run()

The main issue which I am currently facing is I am having issues running with ff.run(). Even though running the same command on command line (using ffmpeg) seems to go flawlessly, when trying to run with ffmpy it gives me "FFRuntime Exited With Status Code 1", and I'm not sure what could be causing this. As I have only just started using ffmpy and ffmpeg I'm not entirely sure what I'm doing is right, so any help would be greatly appreciated.

Daveguy
  • 255
  • 3
  • 11

1 Answers1

0

The attribute ff.cmd is meant to be for reference only after you construct the command. It is the FFmpeg() call that counts toward constructing the command. In your case, your ff creation should look like this:

file_name = "spam"
start_time = '02:10'
end_time = '02:19'
ff = FFmpeg(
    inputs={file_name + ".mp3": None},
    outputs={file_name + "_truncated.mp3":
        '-ss ' + start_time + ' -to ' + end_time + ' -async 1 '})

ff.cmd
>> 'ffmpeg -i spam.mp3 -ss 02:10 -to 02:19 -async 1 spam_truncated.mp3'

For debugging, the call ff.run() takes arguments such as stdout and stderr, which you can leverage to redirect ffmpeg's output to files:

ff.run(
    stdout=open('out.txt', 'w'),
    stderr=open('err.txt', 'w')
)

Review the contents of those files to debug your command.

I'd also suggest looking into Python docs for pathlib (to construct paths more intuitively) and f-strings for readable string formatting.

Basil
  • 659
  • 4
  • 11