import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile import write


def morse(array, dist=10):
    res = np.zeros(dist * array.shape[0])
    for i in range(array.shape[0]):
        if array[i] == 0:
            res[dist * i: dist * (i + 1)] = np.ones(dist, dtype=int)
    return res


def make_sound(array, frequency):
    tmp = np.sin(440 / 2 / np.pi * np.linspace(0, frequency / 70 * 2 * np.pi, 3 * 44100))
    for i in range(array.shape[0]):
        ll = int(tmp.shape[0] / array.shape[0] * i)
        rr = int(tmp.shape[0] / array.shape[0] * (i + 1))
        if array[i] == 0:
            tmp[ll: rr] *= 2
        if array[i] == 1:
            tmp[ll: rr] /= 2
    scaled = np.int16(tmp / np.max(np.abs(tmp)) * 32767)
    return scaled


smile = np.array([[0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 1, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 0, 1, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 1, 0, 0, 0, 0, 1, 0],
                  [0, 0, 1, 0, 0, 1, 0, 0],
                  [0, 0, 0, 1, 1, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0]])

heart = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 1, 0, 0, 0, 1, 0, 0],
                  [0, 1, 1, 1, 0, 1, 1, 1, 0],
                  [0, 1, 1, 1, 1, 1, 1, 1, 0],
                  [0, 1, 1, 1, 1, 1, 1, 1, 0],
                  [0, 0, 1, 1, 1, 1, 1, 0, 0],
                  [0, 0, 0, 1, 1, 1, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0]])

rocket = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                   [0, 0, 0, 0, 1, 1, 0, 1, 0, 0],
                   [0, 0, 0, 1, 0, 0, 0, 1, 0, 0],
                   [0, 0, 1, 0, 0, 0, 1, 1, 0, 0],
                   [0, 0, 1, 0, 0, 1, 1, 1, 0, 0],
                   [0, 0, 0, 0, 1, 1, 0, 1, 0, 0],
                   [0, 0, 0, 1, 1, 0, 0, 1, 0, 0],
                   [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
                   [0, 1, 1, 0, 0, 0, 0, 1, 0, 0],
                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

data = [smile, heart, rocket]
data_resh = [morse(d.flatten()) for d in data]

freq = [220, 440, 880]

res = np.sum(np.array([make_sound(data_resh[i], freq[i]) for i in range(len(data))]), axis=0)
res = np.asarray(res, dtype=np.int64)

plt.plot(res)
plt.show()

write('signal.wav', 44100, res)
