How to use Python audio processing library pydub

WBOY
Release: 2023-05-06 11:58:06
forward
1701 people have browsed it

    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!

    Related labels:
    source:yisu.com
    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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!