import numpy as np
from scipy.signal import hilbert

from synthesis import sample_time, sine
from playback import generate_and_play

def amplitude_envelope(x):
    return abs(hilbert(x))

if __name__ == '__main__':
    
    # Dissonance of two sines f_1 and f_2 is like
    # amplitude modulation of abs(f_1 - f_2) onto mean(f_1, f_2)
    # The amplitude envelope can be obtained as the
    # absolute value of the analytical signal (x + i * h(x))
    # where h is the Hilbert transform.
    # abs(scipy.signal.hilbert(x))
    # It corresponds to the AM demodulation.
    # The beating frequency is 2 * (f_1 - f_2), since its absolute
    # value has twice higher the period.
    t = sample_time(0, 1, 200)
    x = sine(t, 10)  + sine(t, 12)
    e = amplitude_envelope(x)
    plot(t, x)
    plot(t, e)
    # generate_and_play(lambda t: np.sum(sine(t, f) for f in (440, 445)), duration=3)

    # derivative of the amplitude envelope
    # plot(t[:-1], abs(np.diff(abs(hilbert(x)))))

@@ -44,16 +44,28 @@
  hilbert
+%0Aimport math
 %0A%0Afrom s
@@ -193,16 +193,1133 @@
 rt(x))%0A%0A
+def split_to_blocks(x, block_size=1024, hop_size=None, fs=44100):%0A    '''%0A    Splits the input audio signal to block of given size (in samples).%0A    Start position of each block is determined by given hop size.%0A    The last block is right zero-padded if needed.%0A    input:%0A    x - array-like representing the audio signal%0A    '''%0A    if hop_size is None:%0A        hop_size = block_size%0A    block_count = math.ceil(len(x) / hop_size)%0A    def pad(x, size, value=0):%0A        padding_size = size - len(x)%0A        if padding_size:%0A            x = np.pad(x, (0, padding_size), 'constant', constant_values=(0, 0))%0A        return x%0A    blocks = np.vstack(%0A        pad(x%5Bstart:start + block_size%5D, block_size) %5C%0A        for start in range(0, hop_size * block_count, hop_size))%0A    times = np.arange(0, len(x)/fs, hop_size/fs)%0A    return blocks, times%0A%0Adef test_split_to_blocks():%0A    assert np.array(%5B%0A        %5B 0,  1,  2,  3,  4,  5,  6,  7%5D,%0A        %5B 6,  7,  8,  9, 10, 11, 12, 13%5D,%0A        %5B12, 13, 14, 15, 16, 17, 18, 19%5D,%0A        %5B18, 19, 20, 21, 22,  0,  0,  0%5D,%0A    %5D) == split_to_blocks(np.arange(23), 8, 6)%0A        %0A%0A
 if __nam

Split the audio signal into time blocks.