Deleting a specific user voice from the original audio track with Python

CK CK 3776 
Created at
Updated at  
547 0 0

Diarization, also known as speaker diarization, is the process of automatically identifying and separating different speakers in an audio recording. This involves analyzing the acoustic characteristics of the voices, such as pitch, tone, and rhythm, and clustering them into distinct speaker groups. Diarization is used in a variety of applications, including transcription, meeting analysis, and surveillance. 
 
pyannote.audio is a Python library for audio analysis, including speaker diarization. It offers pre-trained models for speaker embedding, clustering, and segmentation, allowing you to automatically separate audio recordings into segments corresponding to different speakers. You can adjust parameters like the number of speakers and the model type to customize the diarization process. Additionally, you can access pre-trained models for other tasks like speaker verification and voice activity detection. 

 

Here's a step-by-step guide using pyannote.audio to perform speaker diarization:

 

Step 1: Install pyannote.audio and Dependencies

You'll need Python 3.8 or 3.9 for compatibility with pyannote.audio. Install the library along with the required dependencies.

pip install pyannote.audio
pip install torch torchvision torchaudio  # for PyTorch (use the right version for your OS)
pip install huggingface_hub

Step 2: Authenticate with Hugging Face

pyannote.audio uses pre-trained models hosted on Hugging Face, so you'll need an access token. You can create one by signing up at Hugging Face and generating a token.

from huggingface_hub import login
login(token="YOUR_HUGGING_FACE_ACCESS_TOKEN")

Step 3: Perform Speaker Diarization

Here's a simple example that loads an audio file, performs diarization, and outputs the timestamps of each speaker's segments.

from pyannote.audio import Pipeline

# Initialize the speaker diarization pipeline
pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization")

# Apply the pipeline to an audio file
diarization_result = pipeline("your_audio_file.wav")

# Display the speaker segments
for turn, _, speaker in diarization_result.itertracks(yield_label=True):
    print(f"Speaker {speaker}: from {turn.start:.1f}s to {turn.end:.1f}s")

The output will provide time intervals during which each speaker is talking. For example:

Speaker 1: from 0.0s to 5.5s
Speaker 2: from 5.5s to 10.3s
Speaker 1: from 10.3s to 15.0s

Step 4: Remove or Modify Specific Speaker Segments

Once you have the timestamps, you can use pydub to load the audio, split it by speaker segments, and then delete or replace specific speaker sections.

Here's an example of removing all segments spoken by "Speaker 1":

from pydub import AudioSegment

# Load the original audio
original_audio = AudioSegment.from_file("your_audio_file.wav")

# Initialize an empty audio segment
output_audio = AudioSegment.empty()

# Add only non-Speaker 1 segments to the output audio
for turn, _, speaker in diarization_result.itertracks(yield_label=True):
    if speaker != "SPEAKER_01":
        segment = original_audio[turn.start * 1000 : turn.end * 1000]
        output_audio += segment

# Export the modified audio
output_audio.export("modified_audio_no_speaker_1.wav", format="wav")

This example removes all segments where Speaker 1 is detected. You can replace segments or add effects similarly, using the timestamps to manipulate the audio selectively.

 

Below case keeps the original duration unlike the above example:

from pydub import AudioSegment

# Load the original audio
original_audio = AudioSegment.from_file("your_audio_file.wav")

# Initialize an empty audio segment with silence
output_audio = AudioSegment.silent(duration=len(original_audio))

# Add only non-Speaker 1 segments to the output audio
for turn, _, speaker in diarization_result.itertracks(yield_label=True):
    if speaker != "SPEAKER_01":
        segment = original_audio[turn.start * 1000 : turn.end * 1000]
        output_audio = output_audio.overlay(segment, position=turn.start * 1000)

# Export the modified audio
output_audio.export("modified_audio_no_speaker_1.wav", format="wav")

Explanation

  • AudioSegment.silent(duration=len(original_audio)) creates an output with the same length as the original but filled with silence.
  • output_audio.overlay(segment, position=turn.start * 1000) adds the non-Speaker 1 segments at the correct positions while preserving silence in the removed sections.

This should retain the original duration of the audio file.

Tags Diarization Overlay Audio Python Audio Processing Speaker Verification pyannote.audio pyannote.segmentation Facebook X
Comments 0
Similar posts
  1. Creating mp3 audio file based on the text input with Python
    461
  2. Implementing Text To Speech / Audio with Python3 and pyttsx3
    353
  3. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,430
  1. Method to maximize full CPU performance with Python
    314
  2. How do I get the maximum available of thread in python?
    978
  3. Using Queue Algorithm with Redis - RPUSH and LPOP
    767
  4. Use cache concept with Redis : Let's do Redis programming with Python
    528
  5. Installing Python 3.8 in a venv environment on CentOS 7
    460
  6. CUDA versus OpenCL
    575
  7. Simple gRPC server based on Python
    392
  8. Python code to convert PDF file to Excel Spreadsheet
    692
  9. Python script to list files on your Google Drive and download one of them
    938
  10. Coinbase Python API - Basic Example
    461
  11. AWS Lambda Code Example based on Python
    333
  12. Python code using GPU on CentOS with AWS
    1,247
  13. Video Scence Detection with PySceneDetect
    2,318
  14. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,430
  15. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    900
  16. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    436
  17. Creating mp3 audio file based on the text input with Python
    461
  18. Implementing Text To Speech / Audio with Python3 and pyttsx3
    353
  19. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  20. Python Simplified Assignment Operators
    533
  21. Trackback module used for Python Threading debugging
    839
  22. Python Flask with simple HTML files to server web pages along with API
    926
  23. Python Flask web server tutorial from the scratch
    618
  24. Simple Web Server based in Python
    366
  25. Thread Implementation in Python
    506
  26. A shell script that activates a Python virtual environment and then runs a specific Python script
    740
  27. Learning about Python Multiprocessing Technique
    590
  28. Simple Example to get the total number of records in BigQuery with Python
    665
  29. Using BigQuery in Python
    407
  30. Python Web Programming based on Django from the Scratch
    366
Recently updated
  1. Why SPF and DKIM Are Essential for Linux Email Servers?
    5
  2. How do I create animated background for Google Meet?
    19,014
  3. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    193
  4. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    75
  5. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    151
  6. Array of arguments passed to script in PHP
    83
  7. Invalid Auction Storms in Ad Tech
    91
  8. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    194
  9. The Two Clocks of Ad Server Architecture
    61
  10. Frequency Cap Architecture Overview
    505
  11. Collecting Proof-of-Play from 100,000 Screens
    139
  12. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    276
  13. What is RedisVL?
    102
  14. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    219
  15. TPU & GPU Cluster Management Tools
    229
  16. The Concept of Scaffolding in AI Agents
    217
  17. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    568
  18. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    246
  19. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    321
  20. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    196
  21. Machine Learning: Training vs. Ranking
    200
  22. The Continuous Learning Machine: Designing a Loop That Actually Turns
    212
  23. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    188
  24. Designing a Data Curation System Around a Vector Database
    213
  25. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    228
  26. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    646
  27. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    181
  28. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    203
  29. Understanding Data Lineage
    251
  30. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    159