import sounddevice as sd
from scipy.io.wavfile import write as write_wav
import os
from os.path import join


def record():
    fs = 44100  # Sample rate
    seconds = 3  # Duration of recording

    recording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
    print(f'BEGIN')
    sd.wait()
    print('END\n----')
    return recording, fs


def record_and_write(word):
    folder = join('new_dataset', word)
    print('sample:', word)
    recording, fs = record()
    write_wav(join(folder, f"{len(os.listdir(folder))}.mp3"), fs, recording)  # Save as WAV file


if __name__ == '__main__':
    if not os.path.exists('new_dataset'): os.mkdir('new_dataset')

    with open('words.txt') as file:
        words = file.readlines()
        words = [word[:-1] for word in words]
    for word in words[:10]:
        folder = join('new_dataset', word)
        if not os.path.exists(folder): os.mkdir(folder)
        l = 10
        for i in range(l):
            print(f'{i}/{l}')
            record_and_write(word)
