编写WAV文件,并为wav文件制作副本

时间:2016-03-23 01:27:54

标签: python wav

我有关于编写WAV文件的问题。 以下是一些信息:

写一个名为filename的WAV文件,有两个通道,两个字节的样本宽度, framerate给出的帧率,len(sound}个样本,压缩类型' NONE'和压缩 姓名' not compressed '

这是我的代码:

import wave
import struct

def loadstereowav(filename):
    w = wave.open(filename, 'r')
    nchannels, sampwidth, framerate, nframes, comptype, compname = w.getparams()
    assert nchannels == 2 and sampwidth == 2 and comptype == 'NONE'
    frames = w.readframes(nframes * nchannels)
    sound = struct.unpack_from((str(nframes)+'h') * nchannels, frames)
    w.close()
    return framerate, sound


def savestereowav(filename, framerate, sound):
    w1 = wave.open(filename, "w")
    for i in range(0, len(sound)):
        w1.write(struct.pack('>h', framerate))

以下是一些测试用例:

>>> rate, sound = loadstereowav('love.wav')
>>> savestereowav('love_copy.wav', rate, sound)

我需要编写一个savestereowav(filename, framerate, sound)函数来加载并保存文件应该生成一个副本。

例如,加载" love.wav "并使用" love_copy.wav "

制作副本

但是,我不知道如何处理WAV文件。

有人帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

如果您需要复制文件而不进行修改(同一nchannels,同一sampwidth等),您可以复制文件而无需分析/了解其内容:shutils.copyfile()应该做的伎俩

另一方面,如果您需要转换数据(例如更改采样率,通道数等),您将需要两件事:

  1. 了解wav文件格式。在网上搜索“wav文件格式”(ex https://en.wikipedia.org/wiki/WAV)。 wave模块仅提供readframes()方法,但您必须手动管理数据。

  2. 根据您想要的转换,您需要某种信号处理方法(例如https://en.wikipedia.org/wiki/Sampling_%28signal_processing%29)。这可能是一个广泛的问题。

  3. 由于您在framerate函数中添加了savestereowav参数,因此我假设您要重新取样。但在您的测试用例中,您使用相同的rate

答案 1 :(得分:0)

据我所知,您已经拥有它了……这只是一个小小的调整。 加载WAV文件时,首先将其打开并检索所有可用参数。您可以决定是否使用它们。实际上,您只需要前四个,即通道数(单声道为1,立体声为2),采样率,采样宽度和帧数。因为此代码中的轨道必须是立体声,否则您会陷入断言的情况,因此必须读取每个声道的帧(立体声的左右声道)。 解压缩为字节然后关闭后,即构成声音。 现在,您拥有克隆或复制WAV文件所需的所有信息。

然后,剩下的就是相反的过程,您需要创建一个新的WAV文件,并在原始轨道中设置相同的参数,然后必须通过pack函数逐帧地编写代码。

import wave, struct

def loadstereowav(filename):
    w = wave.open(filename, 'r')
    nchannels, sample_width, sample_rate, nframes, comptype, compname = w.getparams()
    assert nchannels == 2 and sample_width == 2 and comptype == 'NONE'
    frames = w.readframes(nframes * nchannels)
    sound = struct.unpack_from((str(nframes)+'h') * nchannels, frames)
    w.close()
    return sample_rate, nchannels, sample_width, sound

def savestereowav(filename, sample_rate, n_channels, sample_width, sound):
    # Add file parameters
    w1 = wave.open(filename, "w")
    w1.setnchannels(n_channels)
    w1.setsampwidth(sample_width)
    w1.setframerate(sample_rate)
    for i in range(0, len(sound)):
        w1.writeframesraw(struct.pack('<h', sound[i])) ## Copy each frame

srate, channels, swidth, sound = loadstereowav('Hit.wav')
savestereowav('Hit_copy.wav', srate, channels, swidth, sound)