import numpy as np
import matplotlib.pyplot as plt
import pyroomacoustics as pra
from scipy.io import wavfile
from scipy.io.wavfile import write
from scipy.io.wavfile import read
import os

#############
# Reverberation effect demonstration 
# 22/11/2024 - Silvio Osimi - silvio.osimi@unipr.it 
# try to change rt60, mic_location, and try different anechoic sounds
# Note: pyroomacoustics needs C/C++ building tools for the installation: https://visualstudio.microsoft.com/visual-cpp-build-tools/
# Documentation: https://pyroomacoustics.readthedocs.io/en/pypi-release/pyroomacoustics.room.html
#############



### VARIABILI #######
rt60_tgt = 0.9  # seconds
room_dim = [10, 10, 4]  # meters ( width, length, height )
mic_location = [8, 4, 1.5]  # Posizione del microfono
source_location = [3, 4, 1.5]  # Posizione della sorgente

name = "organ"
############

# import a MONO!! wavfile 
fs, audio = wavfile.read(name + ".wav")

# We invert SABINE's FORMULA to obtain the parameters for the ISM (Image source method)
e_absorption, max_order = pra.inverse_sabine(rt60_tgt, room_dim)
print(e_absorption)


# Create the room
room = pra.ShoeBox(
    room_dim, fs=fs, materials=pra.Material(e_absorption), max_order=max_order
)


# Aggiunta di un microfono nella stanza
room.add_microphone(mic_location)
# Aggiunta di una sorgente sonora nella stanza
room.add_source(source_location, signal=audio)


# Visualizzazione della stanza
room.plot()
# Simulazione dell'acustica della stanza
room.simulate()

# Estrazione del segnale elaborato
processed_signal = room.mic_array.signals[0]
# Salvataggio del segnale elaborato in formato .wav
i = 1
while os.path.exists(name + "_reverb{}.wav".format(i)):
    i += 1
write(name + "_reverb{}.wav".format(i), fs, processed_signal)
# Mostra la forma della stanza
plt.show()
