Python 音频处理相关工具库

import os
from typing import Tuple, List
from pydub import AudioSegment
from pydub.silence import detect_silence
from sdk.utils.util_file import FileProcess
from sdk.utils.util_folder import FolderProcess
from sdk.utils.util_cmd import RunCmd


class VoiceProcess():
    """
    音频处理
    """

    def __init__(self):
        self.file = FileProcess()
        self.cmd = RunCmd()

    def read_vioce(self, file: str) -> AudioSegment:
        """
        读取音频
        :param file:
        :return:
        """
        return AudioSegment.from_file(
            file, format=self.file.get_file_tail(file))

    def get_total_duration(self, audio) -> int:
        """
        获取音频时长
        :param audio:
        :return: 毫秒
        """
        duration = audio.duration_seconds
        return duration * 1000

    def cut_voice(self, audio: AudioSegment, begin: int,
                  end: int) -> AudioSegment:
        """
        切割音频
        :param audio:
        :param begin:毫秒
        :param end:毫秒
        :return:
        """
        return audio[begin:end]

    def merge_videos(self, voice_lists: List[AudioSegment]) -> AudioSegment:
        """
        合并音频
        :param audio1:
        :param audio2:
        :return:
        """
        return sum(voice_lists)

    def save_video(self, audio: AudioSegment, save_file: str):
        """
        保存音频
        :param audio:
        :param save_file:
        :return:
        """
        audio.export(
            save_file,
            format=self.file.get_file_tail(save_file).replace(
                ".",
                ""))

    def adjust_vioce(self, audio: AudioSegment, num: int):
        """
        调整音量
        :param audio:
        :param num:
        :return:
        """
        return audio + num

    def get_sample_rate(self, audio: AudioSegment) -> int:
        """
        获取采样率
        :param audio:
        :return:
        """
        return audio.frame_rate

    def resample_voice(self, audio: AudioSegment, rate: int) -> AudioSegment:
        """
        重采样
        :param audio:
        :param rate:采样率
        :return:
        """
        return audio.set_frame_rate(rate)

    def get_blank_voice(self, audio: AudioSegment,
                        min_len: int = 3000, db: int = -35) -> Tuple[int, int]:
        """
        识别空白音
        :param audio:
        :param db:分贝
        :return: 所有静音片段开始和结束时间
        """
        silence_ranges = detect_silence(audio, db, min_len, 1)
        for start, end in silence_ranges:
            yield (start, end)

    def ms_timedelete(self, millis: int) -> str:
        """
        毫秒转换成 小时:分钟:秒.毫秒 格式
        :param millis:
        :return:
        """
        seconds = int((millis / 1000) % 60)
        minutes = int((millis / (1000 * 60)) % 60)
        hours = int((millis / (1000 * 60 * 60)) % 24)
        lay = millis - hours * 1000 * 60 * 60 - minutes * 1000 * 60 - seconds * 1000
        return "{}:{}:{}.{}".format(
            str(hours).rjust(2, "0"),
            str(minutes).rjust(2, "0"),
            str(seconds).rjust(2, "0"),
            str(lay)
        )

    def voice_time_ms(self, time_voice: str):
        """
        小时:分钟:秒.毫秒 转换成 毫秒
        :param time_voice:
        :return:
        """
        min = time_voice.split(":")[0]
        ms = time_voice.split(".")[-1]
        s = time_voice.split(":")[1].split(".")[0]
        return (60 * int(min) + int(s)) * 1000 + int(ms) * 10

    def get_channels(self, audio: AudioSegment) -> AudioSegment:
        """
        拆分音频声道数据
        :param audio:
        :return:
        """
        return audio.split_to_mono()

    def add_blank_voice(self, audio: AudioSegment, start: int,
                        duration: int = 1000) -> AudioSegment:
        """
        批量在指定时间节点插入空白音频
        :param audio: 待插入音频
        :param start_list: 插入时间节点
        :param duration: 空白音持续时长
        :return:
        """
        blank = AudioSegment.silent(duration)
        new_audio = audio[0:start] + blank + audio[start:]
        return new_audio

    def mix_mp4_mp3(self, mp4: str, mp3: str, out: str,
                    ffmpeg_path: str = None):
        """
        合并音视频
        :param mp4:
        :param mp3:
        :param out:
        :return:
        """
        if not ffmpeg_path:
            self.folder = FolderProcess()
            path = self.folder.split_path(os.path.realpath(__file__), "sdk")
            ffmpeg_path = self.folder.merge_path(
                [path[0], "sdk", "plugins", "ffmpeg", "ffmpeg.exe"])

        cmd = "{} -i {} -i {} -acodec copy -vcodec copy {}".format(
            ffmpeg_path, mp4, mp3, out
        )
        for res in self.cmd.run(cmd):
            yield res

util_cmd.py

# !/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author  : v_jiaohaicheng@baidu.com
@des     :

"""
import subprocess


class RunCmd():
    """

    """

    def __init__(self):
        pass

    def run(self, cmd, encoding="utf-8"):
        """

        :param cmd:
        :param encoding:
        :return:
        """
        p = subprocess.Popen(
            cmd,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            encoding=encoding
        )
        while p.poll() is None:
            out = p.stdout.readline().strip()
            if out:
                yield out

相关推荐

  1. Python 音频处理相关工具

    2023-12-06 05:42:05       39 阅读
  2. 音频处理工具,以及相关开源

    2023-12-06 05:42:05       32 阅读
  3. Python处理音频文件两个非常重要

    2023-12-06 05:42:05       40 阅读
  4. 工业智能】音频信号相关场景

    2023-12-06 05:42:05       32 阅读
  5. python】基于librosa提取音频特征

    2023-12-06 05:42:05       15 阅读
  6. python视频处理工具

    2023-12-06 05:42:05       19 阅读
  7. PyTorch 中音频信号处理torchaudio的详细介绍

    2023-12-06 05:42:05       21 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-06 05:42:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-06 05:42:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-06 05:42:05       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-06 05:42:05       20 阅读

热门阅读

  1. 如何基于OpenCV和Sklearn库开展数据降维

    2023-12-06 05:42:05       34 阅读
  2. soapui报错: CXF directory must be set in global preferences

    2023-12-06 05:42:05       34 阅读
  3. Hadoop学习笔记(HDP)-Part.03 资源规划

    2023-12-06 05:42:05       40 阅读
  4. 前后端接口设计规范

    2023-12-06 05:42:05       39 阅读
  5. [数据结构] 栈和队列C++作业

    2023-12-06 05:42:05       28 阅读
  6. elasticsearch副本和分片

    2023-12-06 05:42:05       37 阅读
  7. CentOS7安装最新版本git

    2023-12-06 05:42:05       33 阅读