为何Python循环仅生成一个摩尔斯码音频文件?
树莓派摩尔斯码音频生成实现(已解决)
我正在做一个树莓派相关的学校项目,目标是生成摩尔斯码音频文件,之后用pifm手动发送。目前已经完成文本转摩尔斯码的功能,现在用Python实现音频文件的生成。
我的实现思路:读取存储摩尔斯码的text.txt文件,获取字符总数后循环遍历每个字符,判断是点(.)还是划(_),分别生成对应时长的正弦波音频文件,每个点/划对应一个独立的WAV文件。
过程中遇到过循环仅能生成单个文件的问题,最初用for x in number_of_characters的写法,后来改成range仍未解决,不过现在已经修正代码,问题得到解决。
最终可用代码:
import numpy as np from scipy.io.wavfile import write file = open("text.txt", "r") l = file.read() number_of_characters = len(l) for x in range(0, number_of_characters): print(f"x: {x}, number_of_characters: {number_of_characters}") if l[x] == '.' : rate = 44100 # Sampling rate [samples/s]. n = 44100 * 1 # Length [samples]. f = 440 # Frequency of the sine [Hz]. t = np.linspace(0, n / rate, n, endpoint=False) s = np.sin(2 * np.pi * f * t) write('sine_' + str(x) + '.wav', rate, np.round(s*32767).astype(np.int16)) elif l[x] == '_': rate = 44100 # Sampling rate [samples/s]. n = 44100 * 2 # Length [samples]. f = 440 # Frequency of the sine [Hz]. t = np.linspace(0, n / rate, n, endpoint=False) s = np.sin(2 * np.pi * f * 2*t) write('sine_' + str(x) + '.wav', rate, np.round(s*32767).astype(np.int16))
注:我在学校主要用Lazarus(Pascal),对Python不太熟悉,若有低级错误请见谅。
内容的提问来源于stack exchange,提问作者kai
相关产品推荐
相关产品推荐

