当前位置:首页 > 播放器资讯 热门

wav音频(wav音频怎么剪辑)

作者:播放器家园 来源:www.bofangqi.org 时间:2022-11-25 点击:0

本文播放器家园分享“wav音频(wav音频怎么剪辑)”!

wav文件是一种无损的音频文件。python读写这种这种文件比较方便,因为python自带有标准库“wave”,可以用来读写这种文件。

import waveimport numpy as npdef my_read_wave(filename: str):    ifile = wave.open(filename)    channels = ifile.getnchannels()    fs = ifile.getframerate()    frames_n = ifile.getnframes()    sample_width = ifile.getsampwidth()    # 获取frames_n帧数据(每帧字节数: sample_width * channels)    # x为字节数组    x = ifile.readframes(frames_n)    ifile.close()    if sample_width == 2:        x = np.frombuffer(x, dtype=np.uint16)  # 字节数组转换成uint16的数组        x = x.astype(np.int16)  # 将uint16数组转换成        x = x.astype(np.float) / (2**15-1)        x = x.reshape((-1, channels))    return x, fsdef my_write_wave(filename:str, x: np.ndarray, fs: int):    ofile = wave.open(filename, "w")    ofile.setsampwidth(2)    ofile.setframerate(fs)    if x.ndim == 1:        ofile.setnchannels(1)    else:        m, n = np.shape(x)        ofile.setnchannels(n)        x = x.flatten()    x = x * (2**15-1)    x = x.astype(np.int16)    x = x.astype(np.uint16)    ofile.writeframesraw(x.tobytes())    ofile.close()

测试一下,读写文件

x, fs = my_read_wave("sounds/castanets.wav")plt.figure()plt.plot(x[:, 0])plt.figure()plt.plot(x[:, 1])my_write_wave("s.wav", x, fs)