5

I have an audio file and I want to split it every 2 seconds. Is there a way to do this with librosa?

So if I had a 60 seconds file, I would split it into 30 two second files.

Hendrik
  • 5,085
  • 24
  • 56

2 Answers2

3

librosa is first and foremost a library for audio analysis, not audio synthesis or processing. The support for writing simple audio files is given (see here), but it is also stated there:

This function is deprecated in librosa 0.7.0. It will be removed in 0.8. Usage of write_wav should be replaced by soundfile.write.

Given this information, I'd rather use a tool like sox to split audio files.

From "Split mp3 file to TIME sec each using SoX":

You can run SoX like this:

 sox file_in.mp3 file_out.mp3 trim 0 2 : newfile : restart

It will create a series of files with a 2-second chunk of the audio each.

If you'd rather stay within Python, you might want to use pysox for the job.

Hendrik
  • 5,085
  • 24
  • 56
2

You can split your file using librosa running the following code. I have added comments necessary so that you understand the steps carried out.

# First load the file
audio, sr = librosa.load(file_name)

# Get number of samples for 2 seconds; replace 2 by any number
buffer = 2 * sr

samples_total = len(audio)
samples_wrote = 0
counter = 1

while samples_wrote < samples_total:

    #check if the buffer is not exceeding total samples 
    if buffer > (samples_total - samples_wrote):
        buffer = samples_total - samples_wrote

    block = audio[samples_wrote : (samples_wrote + buffer)]
    out_filename = "split_" + str(counter) + "_" + file_name

    # Write 2 second segment
    librosa.output.write_wav(out_filename, block, sr)
    counter += 1
    samples_wrote += buffer

[Update]

librosa.output.write_wav() has been removed from librosa, so now we have to use soundfile.write()

Import required library

import soundfile as sf

replace

librosa.output.write_wav(out_filename, block, sr)

with

sf.write(out_filename, block, sr)
eracube
  • 2,484
  • 2
  • 15
  • 18
  • I get this error `AttributeError: module 'librosa' has no attribute 'output'` , when I try to run the line `librosa.output.write_wav(out_filename, block, sr)` – Matt095 Sep 24 '22 at 23:45
  • 1
    I have updated the answer. Now you have to use soundfile library. – eracube Sep 26 '22 at 09:43