import numpy as np
import soundfile as sf
import librosa
import os


class ShortFrameError(BaseException):
    pass


def cut_audio(path, step=22050, frame_len=4):
    """Cuts the audio file of any length into frames.
    
       path - str, path to the audio file;
       step - int, indicates how fast we move framing window (1s = 22050)
       frame_len - int, length of frames (in seconds)
       
       return - numpy array of numpy arrays of ints (amplitudes for certain time moment)"""
    
    res = []
    array, sr = librosa.load(path)
    num_frames = int((len(array) - frame_len * step) / step) + 1
    if len(array) < frame_len * sr:
        raise ShortFrameError(f"Length of the file is {len(array) / sr}s, but minimal length is {frame_len}s")
    for i in range(num_frames):
        res.append(array[i*step:(i+frame_len)*step])
    return np.array(res)


def write_to_folder(array, dest_folder, sr=22050, format=".wav"):
    """Writes cutted audio files to the certain folder.
       
       array - numpy array, array with framed audio files
       dest_folder - str, path to the folder where we write files
       sr - int, sample rate
       format - str, format in which files will be saved"""
       
    for i in range(len(array)):
        sf.write(os.path.join(dest_folder, "frame_" + str(i) + format), array[i], sr)
    print("Files were written successfully.")
