Table of Contents
1. Installation
2. Import and read audio files
3. Play audio
4. Audio duration
5. Audio cutting
6. Audio merge
7. Audio conversion
8. Adjust volume
9. Split audio
10. Complete code
Application case
1. Convert audio files to the specified format
2. Merge multiple audio files into one file
3 . Make ringtones
4. Adjust audio volume
Home Backend Development Python Tutorial How to use Python audio processing library pydub

How to use Python audio processing library pydub

May 06, 2023 am 11:58 AM
python pydub

    1. Installation

    Use pip to install (ffmpeg dependencies also need to be installed, it is recommended to use the conda command to install, you do not need to configure the environment):

    pip install pydub
    Copy after login

    2. Import and read audio files

    from pydub import AudioSegment
    audio = AudioSegment.from_file("path/to/file")
    Copy after login

    3. Play audio

    from pydub.playback import play
    play(audio)
    Copy after login

    4. Audio duration

    duration = audio.duration_seconds # 单位为秒
    Copy after login

    5. Audio cutting

    # 前10秒
    audio = audio[:10000]
    
    # 后10秒
    audio = audio[-10000:]
    
    # 从第10秒开始到第20秒结束
    audio = audio[10000:20000]
    
    # 从第10秒开始到结尾
    audio = audio[10000:]
    
    # 从开始到第10秒audio = audio[:10000]
    Copy after login

    6. Audio merge

    audio1 = AudioSegment.from_file("path/to/file1")
    audio2 = AudioSegment.from_file("path/to/file2")
    audio_combined = audio1 + audio2
    Copy after login

    7. Audio conversion

    audio.export("path/to/new/file", format="mp3")
    Copy after login

    8. Adjust volume

    # 增加10分贝
    louder_audio = audio + 10
    
    # 减小10分贝
    quieter_audio = audio - 10
    Copy after login

    9. Split audio

    # 等分分割,按大概每三分钟进行分割
    for i in range(1, 1000):
        if 3.3 >= (audio.duration_seconds / (60 * i)) >= 2.8:
            number = i
            break
    chunks = audio[::int(audio.duration_seconds / number * 1000 + 1)]  # 切割
    
    # 保存分割后的音频
    for i, chunk in enumerate(chunks):
        chunk.export("path/to/new/file{}.wav".format(title,i), format="wav")
    Copy after login

    10. Complete code

    The following is a complete code that is used to cut the audio before and after, and divide the audio into small segments of appropriate length for saving.

    from pydub import AudioSegment
    
    # 读取音频文件
    audio = AudioSegment.from_file("path/to/file")
    
    # 输出视频时长
    print('视频时长:', audio.duration_seconds / 60)
    
    # 前后切割
    start = int(input('前切割n秒,不切割输入0'))*1000
    end = int(input('后切割n秒,不切割输入0'))*1000
    if start:
        audio = audio[start:-end]
    
    # 计算合适的分割长度
    for i in range(1, 1000):
        if 3.3 >= (audio.duration_seconds / (60 * i)) >= 2.8:
            number = i
            break
    chunks = audio[::int(audio.duration_seconds / number * 1000 + 1)] 
    # 保存分割后的音频
    for i, chunk in enumerate(chunks):
        print('分割后的时长:', chunk.duration_seconds / 60)
        chunk.export("path/to/new/file{}.wav".format(i), format="wav")
    Copy after login

    Application case

    1. Convert audio files to the specified format

    from pydub import AudioSegment
    
    # 读取音频文件
    audio = AudioSegment.from_file("path/to/file")
    
    # 转换为mp3格式并保存
    audio.export("path/to/new/file.mp3", format="mp3")
    Copy after login

    2. Merge multiple audio files into one file

    from pydub import AudioSegment
    
    # 读取音频文件
    audio1 = AudioSegment.from_file("path/to/file1")
    audio2 = AudioSegment.from_file("path/to/file2")
    
    # 合并音频文件并保存
    combined_audio = audio1 + audio2
    combined_audio.export("path/to/new/file", format="wav")
    Copy after login

    3 . Make ringtones

    from pydub import AudioSegment
    
    # 读取音频文件
    audio = AudioSegment.from_file("path/to/file")
    
    # 切割并保存
    start = 10000
    end = 15000
    ringtone = audio[start:end]
    ringtone.export("path/to/new/file", format="mp3")
    Copy after login

    4. Adjust audio volume

    from pydub import AudioSegment
    
    # 读取音频文件
    audio = AudioSegment.from_file("path/to/file")
    
    # 增加10分贝
    louder_audio = audio + 10
    
    # 减小10分贝
    quieter_audio = audio - 10
    
    # 保存调整后的音频
    louder_audio.export("path/to/new/file", format="wav")
    quieter_audio.export("path/to/new/file", format="wav")
    Copy after login

    Case: Split songs in audio by identifying blank sounds

    from pydub import AudioSegment
    from pydub.silence import split_on_silence
    
    # 读取音频文件
    audio = AudioSegment.from_file("audio.mp3", format="mp3")
    
    # 设置分割参数
    min_silence_len = 700  # 最小静音长度
    silence_thresh =-10  # 静音阈值,越小越严格
    keep_silence = 600  # 保留静音长度
    
    # 计算分割数量
    num_segments = int(audio.duration_seconds/60/3)  # 每首歌曲大概三分钟,计算歌曲数量
    
    # 分割音频文件
    for i in range(-10, 0):
        segments = split_on_silence(audio, min_silence_len=min_silence_len, silence_thresh=i, keep_silence=keep_silence)
        if len(segments) <= num_segments:
            print(f"分割成功,共分割出 {len(segments)} 段")
            break
        else:
            print(f"当前阈值为 {i},分割出 {len(segments)} 段,继续尝试")
    Copy after login

    First, we Use the AudioSegment.from_file() method to read the audio file, and set the segmentation parameters min_silence_len, silence_thresh and keep_silence to represent the minimum silence length, silence threshold and retained silence length respectively. Among them, the smaller the silence threshold, the more small segments will be segmented, but mis-segmentation may occur; conversely, the larger the silence threshold, the fewer segments will be segmented, but missed segmentation may occur.

    Then, we calculate the number of divisions num_segments, that is, how many segments the audio file is divided into. Here we assume that each song is about three minutes, and calculate how many segments it needs to be divided into.

    Finally, we use the split_on_silence() method to split the audio file, set the split parameters, and continuously adjust the silence threshold through a loop until the number of segmented segments meets expectations. If the split is successful, jump out of the loop; otherwise, continue trying.

    In short, pydub is a very practical audio processing library that can easily perform audio processing, conversion, merging and other operations. At the same time, pydub also has rich application scenarios, such as making ringtones, adjusting volume, etc. It is worth noting that when using pydub, you need to pay attention to the compatibility issues of audio formats.

    In addition, you can also perform operations such as encoding, decoding, mixing, and resampling of audio through pydub. Below are some common examples of operations.

    Coding, Mixing, Resampling

    1. Codec

    from pydub import AudioSegment
    
    # 读取音频文件
    audio = AudioSegment.from_file("path/to/file")
    
    # 编码
    encoded_audio = audio.set_frame_rate(16000).set_sample_width(2).set_channels(1)
    
    # 解码
    decoded_audio = encoded_audio.set_frame_rate(44100).set_sample_width(4).set_channels(2)
    Copy after login

    2. Mixing

    from pydub import AudioSegment
    
    # 读取音频文件
    audio1 = AudioSegment.from_file("path/to/file1")
    audio2 = AudioSegment.from_file("path/to/file2")
    
    # 混音
    mixed_audio = audio1.overlay(audio2)
    
    # 保存混音后的音频
    mixed_audio.export("path/to/new/file", format="wav")
    Copy after login

    3. Resampling

    from pydub import AudioSegment
    
    # 读取音频文件
    audio =AudioSegment.from_file("path/to/file")
    
    # 重采样为44100Hz
    resampled_audio = audio.set_frame_rate(44100)
    
    # 保存重采样后的音频
    resampled_audio.export("path/to/new/file", format="wav")
    Copy after login

    Through pydub, we can easily perform audio encoding, decoding, mixing, resampling and other operations, further expanding the application scenarios of pydub. It should be noted that when performing audio mixing operations, it is necessary to ensure that the sampling rate, number of sampling bits, and number of channels of the two audio files are the same.

    Finally, summarize the advantages and disadvantages of pydub.

    Advantages:

    Lightweight: pydub is a lightweight audio processing library that is easy to install and use.

    Rich functions: pydub provides a wealth of audio processing functions, including cutting, merging, converting, adjusting volume, encoding and decoding, mixing, resampling, etc.

    Wide application: pydub has a wide range of application scenarios, including audio processing, ringtone production, audio format conversion, speech recognition, etc.

    Disadvantages:

    Limited compatibility with formats: pydub has limited compatibility with audio formats and does not support all audio formats. The audio needs to be converted to a supported format before processing. .

    Mediocre performance: When pydub processes large files, its performance may be average, which requires a certain amount of time and computing resources.

    Does not support streaming processing: pydub does not support streaming processing. The entire audio file needs to be read into the memory, resulting in a large memory footprint.

    To sum up, pydub is a feature-rich and widely used audio processing library. When using pydub, you need to pay attention to the compatibility issues of audio formats, and pay attention to the performance and memory usage when processing large files. If you need to handle more complex audio tasks, you can consider using other more professional audio processing libraries.

    The above is the detailed content of How to use Python audio processing library pydub. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

    PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

    Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

    PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

    Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

    PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

    Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

    VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

    Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

    VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

    How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

    In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

    Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

    VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

    See all articles