gradio音频的初步处理函数

这三个函数都是用于处理音频文件的Python函数,它们分别用于从文件中读取音频、将音频数据写入文件以及将音频数据转换为16位整数格式的WAV文件。下面是对每个函数的解读和功能总结:

### 1. `audio_from_file(filename, crop_min=0, crop_max=100)`

**功能**:这个函数用于从指定的文件中读取音频,并可以选择性地裁剪音频的某个部分。

**参数**:
- `filename`:音频文件的路径。
- `crop_min`:裁剪开始的百分比,默认为0,表示从音频开始处裁剪。
- `crop_max`:裁剪结束的百分比,默认为100,表示到音频结束处裁剪。

**用法**:
- 首先尝试使用`AudioSegment.from_file`从文件中读取音频。
- 如果文件不存在,则检查`ffprobe`是否存在,如果不存在则抛出异常,提示用户安装`ffmpeg`。
- 如果提供了裁剪参数,根据这些参数裁剪音频。
- 最后,将音频数据转换为NumPy数组,并根据音频的通道数调整数组的形状。

### 2. `audio_to_file(sample_rate, data, filename, format="wav")`

**功能**:这个函数用于将音频数据写入到指定的文件中。

**参数**:
- `sample_rate`:音频的采样率。
- `data`:音频数据,可以是NumPy数组。
- `filename`:输出文件的路径。
- `format`:输出文件的格式,默认为"wav"。

**用法**:
- 如果指定的格式是"wav",则先调用`convert_to_16_bit_wav`函数将音频数据转换为16位整数格式。
- 使用`AudioSegment`创建音频对象,并设置相应的采样率、样本宽度和通道数。
- 使用`export`方法将音频数据导出到指定的文件中。

### 3. `convert_to_16_bit_wav(data)`

**功能**:这个函数用于将不同格式的音频数据转换为16位整数格式,这是WAV文件的标准格式之一。

**参数**:
- `data`:原始音频数据的NumPy数组。

**用法**:
- 根据`data`数组的数据类型,进行相应的转换操作。
- 支持从`float`、`int`、`uint`等类型的数据转换为16位整数。
- 如果数据类型已经是16位整数,则直接返回。
- 如果数据类型无法自动转换,则抛出异常。

**总结**:
这三个函数提供了从读取音频文件、处理音频数据到写入音频文件的完整流程。它们可以处理多种数据类型,并确保最终的音频文件符合WAV格式的标准。使用这些函数时,需要确保已经安装了必要的库,如`numpy`和`pydub`,并且`ffmpeg`工具也应该安装在系统中。
 

def audio_from_file(filename, crop_min=0, crop_max=100):
    try:
        audio = AudioSegment.from_file(filename)
    except FileNotFoundError as e:
        isfile = Path(filename).is_file()
        msg = (
            f"Cannot load audio from file: `{'ffprobe' if isfile else filename}` not found."
            + " Please install `ffmpeg` in your system to use non-WAV audio file formats"
            " and make sure `ffprobe` is in your PATH."
            if isfile
            else ""
        )
        raise RuntimeError(msg) from e
    if crop_min != 0 or crop_max != 100:
        audio_start = len(audio) * crop_min / 100
        audio_end = len(audio) * crop_max / 100
        audio = audio[audio_start:audio_end]
    data = np.array(audio.get_array_of_samples())
    if audio.channels > 1:
        data = data.reshape(-1, audio.channels)
    return audio.frame_rate, data


def audio_to_file(sample_rate, data, filename, format="wav"):
    if format == "wav":
        data = convert_to_16_bit_wav(data)
    audio = AudioSegment(
        data.tobytes(),
        frame_rate=sample_rate,
        sample_width=data.dtype.itemsize,
        channels=(1 if len(data.shape) == 1 else data.shape[1]),
    )
    file = audio.export(filename, format=format)
    file.close()  # type: ignore


def convert_to_16_bit_wav(data):
    # Based on: https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.write.html
    warning = "Trying to convert audio automatically from {} to 16-bit int format."
    if data.dtype in [np.float64, np.float32, np.float16]:
        warnings.warn(warning.format(data.dtype))
        data = data / np.abs(data).max()
        data = data * 32767
        data = data.astype(np.int16)
    elif data.dtype == np.int32:
        warnings.warn(warning.format(data.dtype))
        data = data / 65536
        data = data.astype(np.int16)
    elif data.dtype == np.int16:
        pass
    elif data.dtype == np.uint16:
        warnings.warn(warning.format(data.dtype))
        data = data - 32768
        data = data.astype(np.int16)
    elif data.dtype == np.uint8:
        warnings.warn(warning.format(data.dtype))
        data = data * 257 - 32768
        data = data.astype(np.int16)
    elif data.dtype == np.int8:
        warnings.warn(warning.format(data.dtype))
        data = data * 256
        data = data.astype(np.int16)
    else:
        raise ValueError(
            "Audio data cannot be converted automatically from "
            f"{data.dtype} to 16-bit int format."
        )
    return data

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小李飞刀李寻欢

您的欣赏将是我奋斗路上的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值