Python音频处理:创建一个正弦波并保存为wav文件
0. 预备知识
0.1 数字信号基础

0.2 声学概念基础

1. 创建一个正弦波
- 正弦波公式:
y(t)= A * sin(2 * pi * f *t)
A是幅值.
pi是3.14159.
f是频率.
t是样本(也就是横坐标上质点的位置). 由于我们需要将其转换为数字,我们将按采样率进行划分.
-
变量声明
import numpy as np import wave import struct import matplotlib.pyplot as plt # frequency is the number of times a wave repeats a second frequency = 1000 num_samples = 48000 # The sampling rate of the analog to digital convert sampling_rate = 48000.0 amplitude = 16000 file = "test.wav" -
公式:
sine_wave = [np.sin(2 * np.pi * frequency * x/sampling_rate) for x in range(num_samples)]其中,可以看到这里用 x s a m p l i n g _ r a t e {x} \over {sampling\_rate} sampling_ratex来表示正线曲线的
横坐标x,而sine_wave的值也就曲线对应的y值。
2. 保存为wav文件
-
参数设置
nframes=num_samples comptype="NONE" compname="not compressed" nchannels=1 sampwidth=2 -
写入数据
wav_file=wave.open(file, 'w') wav_file.setparams((nchannels, sampwidth, int(sampling_rate), nframes, comptype, compname)) for s in sine_wave: wav_file.writeframes(struct.pack('h', int(s*amplitude)))
主要参考:音频文件基本处理流程
4794



被折叠的 条评论
为什么被折叠?



