下面的代码将一个频率为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()
建立一个并行的 sine_list_y
列表与其他频率通道,设置 nchannels=2
,并在输出循环中使用 for s, t in zip(sine_list_x, sine_list_y):
作为标题子句,而一个正文则有两个 writeframes
呼叫 -- -- 一个用于 s
,一个为 t
. 即,两个通道的对应帧在文件中 "交替"。
例如,见 这个 网页上对所有可能的WAV文件格式进行了详尽的描述,我引用一下。
多声道数字音频样本是以交错波数据的形式存储的 简单来说就是多声道(如立体声和环绕声)波文件的音频样本是通过循环播放每个声道的音频样本来存储的,然后再进入下一个样本时间。 这样做的目的是为了在读取整个文件之前可以播放或流式传输音频文件。当从磁盘上播放一个大文件(可能无法完全放入内存)或通过互联网流式传输文件时,这很方便。下图中的值将按照它们在值栏中列出的顺序(从上到下)存储在Wave文件中。
而下面的表格清楚地显示了通道的样本向左、向右、向左、向右、...。
对于一个产生立体声的例子 .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()
另一个选择是使用SciPy和NumPy库。在下面的例子中,我们产生一个立体声波文件,其中左声道有一个低频音,而右声道有一个高频音。
要安装SciPy,请看。 https:/pypi.orgprojectscipy)。
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