Jacq
Jacq

Reputation: 105

How to save clips of audio stream in Python

Overall I am trying to only save small sections of an .mp3 file, an example such as 00:00:00 - 00:01:35.

I am currently getting a url to an .mp3 and saving it to disk before I attempt to do any editing on the clip. Since there is a high chance that these clips may be of arbitrary length I was looking for a possibility to skip to the section of the clip I would like and edit without the full download present.

I am currently using the requests library in python, I haven't used the stream parameter yet because I do not know if I can seek to different sections in streams.

Current implementation:

def download(url, save_location):
    try:
        audio = requests.get(url)
        with open(save_location, 'wb') as audio_file:
            audio_file.write(audio.content)
    except IOError as err:
        print(err)
        print("There was an error retrieving the data. Check your internet connection and try again.")
        sys.exit(0)
    except KeyboardInterrupt:
        print("\n\nYou have interrupted an active download.\n Cleaning up fines now.")
        os.remove(save_location)
        sys.exit(1)

Upvotes: 1

Views: 1797

Answers (2)

Jacq
Jacq

Reputation: 105

In the end I actually ended up using the python-ffmpeg package which allowed me to set start time and duration of the clip with the flags before I saved the output.

Code:

import ffmpeg

audio_input = ffmpeg.input(url)
audio_output = ffmpeg.output(audio_input, save_location, ss=start_pos, t=duration)
audio_output.run()

Upvotes: 0

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

As far as I know,pydub module can save clips of audio.(Sure,you should use requests module to download a complete sound)

But you should install this module and ffmpeg.

A example for this:

from pydub import AudioSegment
sound = AudioSegment.from_mp3(your_file_name)

StartTime = 0
EndTime = 10*1000 # ms

# save 0 to 10s
Output_MP3 = sound[StartTime,EndTime]
Output_MP3.export(TheSavePath,format="mp3") 

Upvotes: 1

Related Questions