Open In App

How to Concatenate Audio Files in Python

Last Updated : 06 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Introduction

Concatenating audio files is a common task in audio processing, and it can be done easily using Python. In this article, we will go over how to concatenate audio files using the pydub module.

Installation

pip install pydub

Approach

  • Install the pydub module using pip and then import the module using from keyword in Python.
  • Enter your mp3 audio file location 
  • Type the start min or start seconds and end minute or end seconds
  • Type the location where you want to save your mp3 file

Implementation of the Program

Python3




from pydub import AudioSegment
 # enter the path of your audio file
sound1 = AudioSegment.from_mp3("/home/dachman/Desktop/Test/walker.mp3")
sound2 = AudioSegment.from_mp3("/home/dachman/Desktop/Test/alone.mp3")
 
def choose_option():
    print("Audio file editing by pydub Package\n")
    print("1. Audio Cut ") ;
    print("2. Sound Increase and Decrease") ;
    print("3. Merge Two Songs") ;
    choose = int(input("Choose Option = "))
    if choose == 1:
        audio_cut()
    elif choose == 2:
        sound_Increase()
    elif choose == 3:
        merge_two_songs()
    elif choose >3:
        print("You Choose Wrong Input") ;
 
def audio_cut():
   
      StrtMin = int(input("Enter the Start Min " ))
      StrtSec = int(input("Enter the Start Sec "))
 
      EndMin = int(input("Enter the End Min "))
      EndSec = int(input("Enter the End Sec "))
 
      sound2 = int(input("Sound Increase or Sound Decrease example 5 or -5 "))
 
    StrtTime = StrtMin*60*1000+StrtSec*1000
     EndTime = StrtMin*60*1000+EndSec*1000
 
     print("Extracting Sound from your audio file")
     extract = sound[StrtTime:EndTime]
 
# Saving file in required location
def sound_Increase():
     if sound2>=0:
          loudmusic = extract + sound2
          loudmusic.export("/home/dachman/Desktop/walker2.mp3", format="mp3")
     else:
          lowmusic = extract - sound2
          lowmusic.export("/home/dachman/Desktop/walker2.mp3",format="mp3")
 
# merge two audio
def merge_two_songs():
      print("Sound Overlay")
     sound3 = sound.append(sound2,crossfade=1500)
     sound3.export("/home/dachman/Desktop/merge_sound",format="mp3")
   
choose_option()


Output

Altering audio using pydub.

Altering audio using pydub.

Alternative Options

Besides pydub, there are other Python libraries that can be used for audio processing, such as scipy, librosa, and audioread. Each of these libraries has its own set of features and capabilities, so it’s important to choose the one that best fits your needs.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads