Karpus-Strongアルゴリズム(K-Sアルゴリズム)を↓ページのブロック線図に基づきJuliaで実装した. https://ccrma.stanford.edu/~jos/pasp/Karplus_Strong_Algorithm.html
実行すると生成波形のグラフが表示され音が再生される.
↓生成波形例
以下ソース.
using Random using Plots using WAV using FFTW mutable struct DelayLine _len::Int mem::Vector{Float64} ptr::Int dl_io_do::Function DelayLine(_len) = new(_len, zeros(_len), 1) end function dl_io_do(dl, mem_in) ptr_next = dl.ptr % dl._len + 1 mem_out = dl.mem[ptr_next] dl.mem[dl.ptr] = mem_in dl.ptr = ptr_next return mem_out end function main() fs = 8000 t_snd = 1 n_delay = 60 delay1 = DelayLine(n_delay) z1 = DelayLine(1) rng = MersenneTwister() wnoise = randn(rng, Float64, delay1._len) delay1.mem = wnoise ./ maximum(abs, wnoise) # display(plot(delay1.mem, show = true)) output = 0 n_calc = fs * t_snd outputs = zeros(n_calc) for _i = 1:n_calc d1o = dl_io_do(delay1, output) z1o = dl_io_do(z1, d1o) output = d1o / 2 + z1o / 2 outputs[_i] = output end wavplay(outputs, fs) display(plot(outputs)) savefig("KS_wave.png") end main()
上記コードの修正
main関数内のコードを以前はトップレベルに書いていた("function main()"とそれに対応する"end"と"main()"の行が無い状態)が、
それを実行すると↓のようなエラーが出たから、関数化してみたら動いた。
この修正方法があっているかわからないが動いたからヨシ
LoadError: UndefVarError: output not defined in expression starting at D:\Users\USERNAME\Documents\Julia\KS.jl:39 top-level scope at KS.jl:40 eval at boot.jl:360 [inlined] include_string(mapexpr::typeof(identity), mod::Module, code::String, filename::String) at loading.jl:1116