基于时间变量不断变化的正弦音调
#Sine wave calculations by vegaseat.
#The program will take in the current time that the computer has, and turn that into a
#tone that is unique to that moment in time. It then makes an accompaning graph to
#view for easier comparison of the sound and an interesting view of the sound heard.
from Tkinter import *
from struct import pack
from math import sin, pi
import math
import time
import os
def wave():
#time based variables
t = time.strftime("%S", time.localtime())
ti = time.strftime("%M", time.localtime())
tis = float(t)
tis = tis / 100
tim = float(ti)
tim = tim / 100
root = Tk()
root.title("The moment")
#variables for canvas
width = 800
height = 600
center = height//2
x_increment = 2
# width stretch
x_factor1 = tis
x_factor2 = tim
# height stretch
y_amplitude = 50
#new canvas
c = Canvas(width=width, height=height, bg="black")
c.pack()
str1 = "sin(x)=white"
c.create_text(10, 20, anchor=SW, text=str1)
center_line = c.create_line(0, center, width, center, fill="red")
# create the coordinate list for the sin() curve, have to be integers
xy1 = []
xy2 = []
for x in range(400):
# x coordinates
xy1.append(x * x_increment)
xy2.append(x * x_increment)
# y coordinates
xy1.append(int(math.sin(x * x_factor1) * y_amplitude) + center)
xy2.append(int(math.sin(x * x_factor2) * y_amplitude) + center)
#create the lines
sinS_line = c.create_line(xy1, fill="white")
sinM_line = c.create_line(xy2, fill="yellow")
root.mainloop()
def au_file(name, freq, freq1, dur, vol):
fout = open(name, "wb")
# header needs size, encoding=2, sampling_rate=8000, channel=1
fout.write(".snd" + pack(">5L", 24, 8*dur, 2, 8000, 1))
factor = 2 * pi * freq/8000
factor1 = 2 * pi * freq1/8000
# write data
for seg in range(8 * dur):
# sine wave calculations
sin_seg = sin(seg * factor) + sin(seg * factor1)
fout.write(pack("b", vol * 64 * sin_seg))
fout.close()
#time based variables
t = time.strftime("%S", time.localtime())
ti = time.strftime("%M", time.localtime())
tis = float(t)
tis = tis * 100
tim = float(ti)
tim = tim * 100
os.startfile("timeSound.au")
#running it using main.
def main():
au_file(name="timeSound.au", freq=tim, freq1=tis, dur=1000, vol=1.0)
wave()
main()
这是我的程序,它会根据输入的分钟数生成一个正弦波音调,并且这个音调会随着时间变化(有点像)。程序会创建一个声音文件,然后播放出来。我想要的是一个实时的正弦波音调,这个音调会根据时间的变化(精确到毫秒)不断波动。这样做可能吗?如果可以的话,我该用什么工具来实现实时播放声音?还有,怎么才能让这些变量和时间连接起来,并且也能实时更新呢?
1 个回答
1
这里有一种处理连续变化频率的方法:
def gen_scale(samples_per_wave, samples_per_change):
pi2 = 2 * math.pi
rad = 0
while (samples_per_wave > 1):
for i in range(0, samples_per_change):
yield math.sin(rad)
rad = rad + pi2 / samples_per_wave
if (rad > pi2):
rad = rad - pi2
samples_per_wave = samples_per_wave - 1
samples_per_wave
实际上是频率(赫兹,Hz)的倒数(也就是说,这个声音的频率会逐渐增加)。samples_per_change
则是生成器在逐步调整频率之前会产生多少个样本。