# Mixing two samples together..

How can I mix two samples together (i.e. mix paste) with a lua script without clipping the sample.

For example combining ‘sample A’ and ‘sample B’ to make a new ‘sample C’ which is an equal mix of A & B.

At the moment I have:

for n = 1, sample_size, 1
sample_c[n] = sample_a[n] + sample_b[n]
end

Which clips the data, I then try

for n = 1, sample_size, 1
sample_c[n] = (sample_a[n] + sample_b[n]) / 2
end

Which halves the volume and doesn’t sound right.

Can anyone help me with how to do this properly so it sounds like the mix paste function in the sample editor?

Thanks

If you’re referring to the ‘Mix (Add)’ mode, then Renoise doesn’t do anything special. It simply adds both signals together: c = a + b

It will definitely clip if signals a and b are loud enough.

If you’re referring to the ‘Modulate (Multiply)’ mode, then it’s nothing special here, either. It’s simply: c = a * b

If you want to add two signals together and ensure that they never clip, then you’ll need to analyse things first to find the peak amplitude, then calculate the correct scaling factor based on this.

For example:

``````
-- find peak level
local peak_level = 0.0
for n = 1, sample_size, 1
local level = math.abs(sample_a[n] + sample_b[n])
if level > peak_level then
peak_level = level
end
end

-- check for clipping
if peak_level > 1.0 then

-- mix and scale to avoid clipping
local scaling = 1.0 / peak_level
for n = 1, sample_size, 1
sample_c[n] = (sample_a[n] + sample_b[n]) * scaling
end

else

-- mix without scaling
for n = 1, sample_size, 1
sample_c[n] = sample_a[n] + sample_b[n]
end

end

``````

Thanks, thats exactly what I was looking for.

Cheers

Just noticed a small typo in my psuedo-code.

This line:

``````local level = math.abs(sample_a[n]) + math.abs(sample_b[n])
``````

Should be changed to this:

``````local level = math.abs(sample_a[n] + sample_b[n])
``````