使用Go播放音频：谐波

傅立叶加法

func FourierTable(nharms int, amps []float64, length int, phase float64) []float64 {
table := make([]float64, length+2)
phase *= tau

for i := 0; i < nharms; i++ {
for n := 0; n < len(table); n++ {
amp := 1.0
if i < len(amps) {
amp = amps[i]
}
angle := float64(i+1) * (float64(n) * tau / float64(length))
table[n] += (amp * math.Cos(angle+phase))
}
}
return normalize(table)
}

// Adjust angle for harmonic 'i' -> move N times forward in the wave
angle := float64(i+1) * (float64(n) * tau / float64(length))
// Add wave amplitude for harmonic 'i' to existing wave (table[n])
table[n] += (amp * math.Cos(angle+phase))

产生谐波

func SquareTable(nharms, length int) []float64 {
amps := make([]float64, nharms)
for i := 0; i < len(amps); i += 2 {
amps[i] = 1.0 / float64(i+1)
}
return FourierTable(nharms, amps, length, -0.25)
}

func SawTable(nharms, length int) []float64 {
amps := make([]float64, nharms)
for i := 0; i < len(amps); i++ {
amps[i] = 1.0 / float64(i+1)
}
return FourierTable(nharms, amps, length, -0.25)
}

func TriangleTable(nharms, length int) []float64 {
amps := make([]float64, nharms)
for i := 0; i < nharms; i += 2 {
amps[i] = 1.0 / (float64(i+1) * float64(i+1))
}
return FourierTable(nharms, amps, length, 0)
}

go run main.go -d 4 -s square -a 0.8 -h 6 -f 440 -o output.wav

image