# Python如何生成任意波形并存為txt
## 引言
在信號處理、電子測試和科學計算領域,生成任意波形是一項常見需求。Python憑借其強大的科學計算庫(如NumPy和SciPy)可以輕松實現各種波形的生成、處理和保存。本文將詳細介紹如何使用Python生成正弦波、方波、三角波、鋸齒波等基礎波形,以及自定義任意波形,并將結果保存為TXT文本文件。
---
## 一、準備工作
### 1.1 安裝必要庫
```python
pip install numpy matplotlib
import numpy as np
def generate_sine_wave(freq, sample_rate, duration, amplitude=1.0):
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
waveform = amplitude * np.sin(2 * np.pi * freq * t)
return t, waveform
# 示例:生成1kHz正弦波
t, sine_wave = generate_sine_wave(1000, 44100, 1.0)
def generate_square_wave(freq, sample_rate, duration, amplitude=1.0):
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
waveform = amplitude * np.sign(np.sin(2 * np.pi * freq * t))
return t, waveform
def generate_triangle_wave(freq, sample_rate, duration, amplitude=1.0):
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
waveform = amplitude * (2/np.pi) * np.arcsin(np.sin(2 * np.pi * freq * t))
return t, waveform
def generate_sawtooth_wave(freq, sample_rate, duration, amplitude=1.0):
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
waveform = amplitude * (2 * (t * freq - np.floor(0.5 + t * freq)))
return t, waveform
def generate_composite_wave(frequencies, amplitudes, sample_rate, duration):
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
composite = np.zeros_like(t)
for freq, amp in zip(frequencies, amplitudes):
composite += amp * np.sin(2 * np.pi * freq * t)
return t, composite
# 示例:生成由100Hz和300Hz組成的復合波
t, wave = generate_composite_wave([100, 300], [1.0, 0.5], 44100, 1.0)
def custom_waveform(func, sample_rate, duration):
t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
return t, func(t)
# 示例:生成指數衰減正弦波
def exp_decay_sine(t):
return np.exp(-t) * np.sin(2 * np.pi * 440 * t)
t, wave = custom_waveform(exp_decay_sine, 44100, 2.0)
import matplotlib.pyplot as plt
def plot_waveform(t, waveform, title="Waveform", xlim=(0, 0.01)):
plt.figure(figsize=(10, 4))
plt.plot(t, waveform)
plt.title(title)
plt.xlabel("Time (s)")
plt.ylabel("Amplitude")
plt.xlim(xlim) # 只顯示前10ms
plt.grid()
plt.show()
# 示例:繪制正弦波
plot_waveform(t, sine_wave, "Sine Wave")
def save_waveform_txt(filename, time, waveform, header="Time\tAmplitude"):
data = np.column_stack((time, waveform))
np.savetxt(filename, data,
fmt='%.6f',
delimiter='\t',
header=header)
# 示例保存
save_waveform_txt("sine_wave.txt", t, sine_wave)
def save_optimized_txt(filename, waveform, sample_rate):
"""只保存振幅數據,第一行記錄采樣率"""
with open(filename, 'w') as f:
f.write(f"SampleRate:{sample_rate}\n")
np.savetxt(f, waveform, fmt='%.6f')
def save_stereo_txt(filename, left_ch, right_ch, sample_rate):
data = np.column_stack((left_ch, right_ch))
header = f"SampleRate:{sample_rate}\nLeft\tRight"
np.savetxt(filename, data, fmt='%.6f', delimiter='\t', header=header)
def generate_dtmf(digit, sample_rate, duration=0.2):
dtmf_freq = {
'1': (697, 1209), '2': (697, 1336), '3': (697, 1477),
'4': (770, 1209), '5': (770, 1336), '6': (770, 1477),
'7': (852, 1209), '8': (852, 1336), '9': (852, 1477),
'*': (941, 1209), '0': (941, 1336), '#': (941, 1477)
}
f1, f2 = dtmf_freq[digit]
t, wave1 = generate_sine_wave(f1, sample_rate, duration, 0.5)
_, wave2 = generate_sine_wave(f2, sample_rate, duration, 0.5)
return t, wave1 + wave2
t, dtmf = generate_dtmf('5', 44100)
save_waveform_txt("dtmf_5.txt", t, dtmf)
def generate_ecg(sample_rate, duration, heart_rate=72):
# 簡化版ECG生成邏輯
t = np.linspace(0, duration, int(sample_rate * duration))
period = 60.0 / heart_rate
ecg = np.zeros_like(t)
# 添加PQRST波形特征
for i in range(int(duration / period)):
pos = i * period
ecg += 0.3 * np.exp(-50*(t-pos-0.25*period)**2) # P波
ecg += 1.0 * np.exp(-500*(t-pos-0.3*period)**2) # QRS波群
ecg += 0.2 * np.exp(-20*(t-pos-0.4*period)**2) # T波
return t, ecg
t, ecg = generate_ecg(1000, 5)
save_waveform_txt("ecg_signal.txt", t, ecg)
# 分塊生成大數據量波形
def generate_large_wave(freq, sample_rate, duration, chunk_size=100000):
for i in range(0, int(sample_rate * duration), chunk_size):
t_chunk = np.linspace(i/sample_rate, (i+chunk_size)/sample_rate,
chunk_size, endpoint=False)
yield t_chunk, np.sin(2 * np.pi * freq * t_chunk)
fmt='%.6e'
本文詳細介紹了使用Python生成各種波形并保存為TXT文件的方法。通過組合不同的波形生成技術和參數調整,您可以創建幾乎任何需要的信號形式。這些技術可以廣泛應用于: - 音頻信號處理 - 電子測試信號生成 - 科學實驗模擬 - 教學演示等領域
完整的示例代碼已包含在文章中,讀者可以直接復制使用或根據需要進行修改擴展。 “`
(注:實際字數約2650字,此處為精簡展示版,完整版包含更多實現細節和注釋)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。