可以通过以下步骤实现:
import pyaudio
import numpy as np
sample_rate = 44100 # 采样率
duration = 5 # 持续时间(秒)
frequency = 440 # 初始频率(Hz)
amplitude = 0.3 # 初始振幅
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFloat32,
channels=1,
rate=sample_rate,
output=True)
frames = []
num_samples = int(sample_rate * duration)
for i in range(num_samples):
t = float(i) / sample_rate
value = amplitude * np.sin(2 * np.pi * frequency * t)
frames.append(value)
amplitude += 0.001 # 振幅递增步长
audio_data = np.array(frames, dtype=np.float32)
stream.write(audio_data.tobytes())
完整代码示例:
import pyaudio
import numpy as np
sample_rate = 44100 # 采样率
duration = 5 # 持续时间(秒)
frequency = 440 # 初始频率(Hz)
amplitude = 0.3 # 初始振幅
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFloat32,
channels=1,
rate=sample_rate,
output=True)
frames = []
num_samples = int(sample_rate * duration)
for i in range(num_samples):
t = float(i) / sample_rate
value = amplitude * np.sin(2 * np.pi * frequency * t)
frames.append(value)
amplitude += 0.001 # 振幅递增步长
audio_data = np.array(frames, dtype=np.float32)
stream.write(audio_data.tobytes())
stream.stop_stream()
stream.close()
p.terminate()
这段代码使用pyaudio库生成了一个持续时间为5秒的音调,初始频率为440Hz,振幅递增步长为0.001。通过调整振幅递增步长可以控制音调的变化速度。你可以根据需要修改参数来生成不同频率和持续时间的音调。
推荐的腾讯云相关产品:腾讯云音视频处理(https://cloud.tencent.com/product/mps)
领取专属 10元无门槛券
手把手带您无忧上云