Cabbage Logo
Back to Cabbage Site

Creating sound sample for sample with a loop

I would like to create a sound signal one sample value at a time by means of a loop. The process should run like this:

  1. Ask for the start values of x_old and v_old.
  2. Calculate x_new and v_new from x_old and v_old by means of certain recursive relations.
  3. Export x_new as the current audio sample value.
  4. Rename x_new and v_new to x_old and v_old .
  5. Goto 2.

The loop should take exactly one sample time long, so that one sample value is produced during one sample time.

Is there a way to do this in Csound?

Looks like this kind of implicit loop will do the trick?:

<CsoundSynthesizer>

<CsOptions>
-odac
</CsOptions>

<CsInstruments>
sr = 44100
ksmps =  1
nchnls = 2
0dbfs = 1

instr 1
kf = 440
kres timeinsts
aOut = sin(2*$M_PI*kf*kres)
outs aOut, aOut
endin
</CsInstruments>

<CsScore>
i 1 0 6
</CsScore>

</CsoundSynthesizer>

yes, ksmps = 1 is the key :+1:

Thanks! :slightly_smiling_face:

<CsoundSynthesizer>

<CsOptions>

-o dac

</CsOptions>

<CsInstruments>

sr = 44100

ksmps = 1

nchnls = 2

0dbfs = 1

instr 1

;steps of 1 sample time

kdelta_t = 1/sr

;input R/m

ka = 7643021

;measuring time passed

kres timeinsts

if kres < 0.0001 then

kx_old = 1.0

kv_old = 0

else

kx_new = kx_old + kv_old*kdelta_t

kv_new = kv_old + -1*ka*kx_old*kdelta_t

kx_old = kx_new

kv_old = kv_new

endif

;correction of amplitude drift

kx_old limit kx_old, -1, 1

aOut = kx_old

outs aOut, aOut

endin

</CsInstruments>

<CsScore>

i 1 0 5

</CsScore>

</CsoundSynthesizer>

The above was what I planned to do, and it’s working now by giving a harmonic signal except for one thing: the amplitude keeps on rising if not checked by limiting the signal (as I have done here by means of the limit opcode). Why doesn’t the amplitude stay at the starting value?

From a quick glance it seems that you have feedback with multiplication. This line is causing the blowup:

kv_new = kv_old + -1*ka*kx_old*kdelta_t

add and printk under it and see how it grows…

kv_new = kv_old + -1*ka*kx_old*kdelta_t
printk .2, kv_new

I’m trying to do something similar as this: https://evgenii.com/blog/programming-harmonic-oscillator/ (see 3. and further)

But I don’t have the moving picture and I’m using Csound. There is also feedback on the web application but no blowup there…

Looks interesting. I don’t have time to delve into it right now, but I’m sure it’s just a simple mistake in your code. That line is clearly a problem.

Problem solved with sr = 300000000 and “Render to file” which gives a wav file with a nice constant harmonic signal with hardly any distortion (no limiting needed any more):

Begin of signal:

End of signal: