14

以下代码将频率为 400Hz 的简单正弦写入单声道 WAV 文件。应如何更改此代码以生成立体声WAV 文件。第二个频道应该在不同的频率。

import math
import wave
import struct

freq = 440.0
data_size = 40000
fname = "WaveTest.wav"
frate = 11025.0  # framerate as a float
amp = 64000.0     # multiplier for amplitude

sine_list_x = []
for x in range(data_size):
    sine_list_x.append(math.sin(2*math.pi*freq*(x/frate)))

wav_file = wave.open(fname, "w")

nchannels = 1
sampwidth = 2
framerate = int(frate)
nframes = data_size
comptype = "NONE"
compname = "not compressed"

wav_file.setparams((nchannels, sampwidth, framerate, nframes,
    comptype, compname))

for s in sine_list_x:
    # write the audio frames to file
    wav_file.writeframes(struct.pack('h', int(s*amp/2)))

wav_file.close()
4

3 回答 3

10

sine_list_y使用另一个频率/频道 set构建一个并行列表nchannels=2,并在输出循环for s, t in zip(sine_list_x, sine_list_y):中用作标题子句,以及一个带有两个writeframes调用的主体 - 一个 for s,一个 for t。IOW,文件中两个通道“交替”的相应帧。

有关所有可能的 WAV 文件格式的详细说明,请参见此页面,我引用

多通道数字音频样本存储为隔行扫描波数据,这意味着多通道(例如立体声和环绕声)波形文件的音频样本是通过在前进到下一个样本之前循环遍历每个通道的音频样本来存储的时间。这样做是为了在读取整个文件之前播放或流式传输音频文件。这在从磁盘播放大文件(可能不完全适合内存)或通过 Internet 流式传输文件时非常方便。下图中的值将按照它们在值列中列出的顺序(从上到下)存储在 Wave 文件中。

下表清楚地显示了通道的样本向左、向右、向左、向右……

于 2010-09-03T15:47:17.800 回答
3

有关生成立体声.wav文件的示例,请参阅test_wave.py模块。测试生成一个全零文件。您可以通过插入交替的样本值来进行修改。

nchannels = 2
sampwidth = 2
framerate = 8000
nframes = 100

# ...

    def test_it(self):
        self.f = wave.open(TESTFN, 'wb')
        self.f.setnchannels(nchannels)
        self.f.setsampwidth(sampwidth)
        self.f.setframerate(framerate)
        self.f.setnframes(nframes)
        output = '\0' * nframes * nchannels * sampwidth
        self.f.writeframes(output)
        self.f.close()
于 2010-09-03T15:56:56.817 回答
1

另一种选择是使用 SciPy 和 NumPy 库。在下面的示例中,我们生成了一个立体声文件,其中左声道具有低频音调,而右声道具有高频音调。

要安装 SciPy,请参阅: https ://pypi.org/project/scipy/

import numpy as np
from scipy.io import wavfile

# User input
duration=5.0
toneFrequency_left=500 #Hz (20,000 Hz max value)
toneFrequency_right=1200 #Hz (20,000 Hz max value)

# Constants
samplingFrequency=48000

# Generate Tones
time_x=np.arange(0, duration, 1.0/float(samplingFrequency))
toneLeft_y=np.cos(2.0 * np.pi * toneFrequency_left * time_x)
toneRight_y=np.cos(2.0 * np.pi * toneFrequency_right * time_x)

# A 2D array where the left and right tones are contained in their respective rows
tone_y_stereo=np.vstack((toneLeft_y, toneRight_y))

# Reshape 2D array so that the left and right tones are contained in their respective columns
tone_y_stereo=tone_y_stereo.transpose()

# Produce an audio file that contains stereo sound
wavfile.write('stereoAudio.wav', samplingFrequency, tone_y_stereo)

环境注意事项

使用的版本 Python 3.7.1

  • Python 3.7.1
  • SciPy 1.1.0
于 2020-05-18T20:52:25.360 回答