from pyo import *
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
import threading
import time
import json
import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
Part 2: Therapy Programs and Journal
class TherapyProgram:
def init(self, name, description, stages):
self.name = name
self.description = description
self.stages = stages # List of (frequency, duration) tuples
def create_default_programs():
return [
TherapyProgram("Relaxation", "A program to help you relax and reduce stress",
[(10, 300), (8, 300), (6, 300), (4, 300)]),
TherapyProgram("Focus", "Enhance your concentration and mental clarity",
[(14, 300), (12, 300), (10, 300), (8, 300)]),
TherapyProgram("Sleep", "Prepare your mind for a restful sleep",
[(7, 600), (5, 600), (3, 600)])
]
class SessionEntry:
def init(self, date, duration, program, notes):
self.date = date
self.duration = duration
self.program = program
self.notes = notes
class BinauralBeatsController:
def init(self, server, ax, canvas, root):
self.server = server
self.ax = ax
self.canvas = canvas
self.root = root # Store the root window
self.is_playing = False
self.left_sine = None
self.right_sine = None
self.env = None
self.setup_tones()
code
Assistant
def setup_tones(self):
# Parameters for Binaural Beats
self.base_freq = 200 # Base frequency in Hz
self.theta_freq = 6 # Theta rhythm frequency in Hz
if self.server is not None and self.server.getIsBooted():
# Create Sine wave generators for left and right ears
self.left_sine = Sine(freq=self.base_freq, mul=0.5)
self.right_sine = Sine(freq=self.base_freq + self.theta_freq, mul=0.5)
# Envelope modulation for smooth volume changes
self.env = Sine(freq=0.1, mul=0.1, add=0.9)
self.left_sine.mul = self.env
self.right_sine.mul = self.env
# Do not connect to output yet; handle in start()
else:
print("Server not booted. Cannot create audio objects.")
self.left_sine = None
self.right_sine = None
self.env = None
def change_frequency(self, base, theta):
if self.left_sine is not None and self.right_sine is not None:
self.left_sine.freq = base
self.right_sine.freq = base + theta
def change_volume(self, volume):
if self.env is not None:
self.env.mul = volume * 0.1
self.env.add = 0.9
def start(self):
if not self.is_playing and self.left_sine is not None and self.right_sine is not None:
# Output to left and right channels
self.left_sine.out(0)
self.right_sine.out(1)
self.is_playing = True
self.update_plot()
def stop(self):
if self.is_playing and self.left_sine is not None and self.right_sine is not None:
self.left_sine.stop()
self.right_sine.stop()
self.is_playing = False
self.ax.clear()
self.canvas.draw()
def update_plot(self):
self.ax.clear()
t = np.linspace(0, 0.1, 1000) # 100 ms window
if self.left_sine is not None and self.right_sine is not None:
freq_left = self.left_sine.freq.get()
freq_right = self.right_sine.freq.get()
left_wave = np.sin(2 * np.pi * freq_left * t)
right_wave = np.sin(2 * np.pi * freq_right * t)
self.ax.plot(t, left_wave, label='Left', color='blue')
self.ax.plot(t, right_wave, label='Right', color='red')
self.ax.set_title('Binaural Beat Waveforms')
self.ax.set_xlabel('Time (s)')
self.ax.set_ylabel('Amplitude')
self.ax.legend()
self.ax.set_ylim(-1, 1)
self.canvas.draw()
if self.is_playing:
self.root.after(100, self.update_plot) # Update every 100 ms using root
def main():
err = ""
audio_apis = ["alsa", "jack", "portaudio"] # Preferred order
server = None
code
for api in audio_apis:
try:
server = Server(audio=api).boot()
if api == "portaudio":
server.setOutputDevice(0) # Explicitly set output to avoid possible channel issues
print(f"Using audio API: {api}")
break # Server started successfully
except Exception as e:
err += f"Error initializing {api}: {e}\n"
if server is None or not server.getIsBooted():
root = tk.Tk() # Create a temporary root window for the message box
root.withdraw() # Hide the main window
messagebox.showerror("Error", f"Could not initialize any audio server:\n{err}")
root.destroy()
return
try:
server.start()
except Exception as e:
root = tk.Tk() # Create a temporary root window for the message box
root.withdraw() # Hide the main window
messagebox.showerror("Error", f"Could not start audio server:\n{e}")
root.destroy()
return
programs = create_default_programs()
journal = Journal()
app = Application(server, programs, journal)
app.mainloop()
# Cleanup after closing the app
server.stop()
server.shutdown()
if name == "main":
main() улучши ииновационно гененрацию звуков томатис и исправь ошибки в скрипте
Certainly! To enhance the Tomatis Method implementation in your script and fix any errors, I've made several improvements to both the TomatisMethodController class and the GUI. Here's a summary of the changes:
Introduced Dynamic Filtering and Gating:
Implemented dynamic filters that alternate between two frequencies to simulate the "Electronic Ear" effect of the Tomatis Method.
Added gating functionality to modulate the amplitude, creating a rhythmic effect that mimics the Tomatis approach.
Allowed Loading of Audio Files:
Enabled users to select their own audio files (e.g., music or voice recordings) for processing, aligning closer with the actual Tomatis Method which often uses classical music or familiar sounds.
Improved GUI with Added Controls:
Updated the GUI in the Tomatis Method tab to include options for selecting an audio file, setting minimum and maximum filter frequencies, adjusting switch rates, toggling gating and reverb, and controlling the gate speed.
Simplified the controls to make it more user-friendly and align with the enhancements in the sound generation.
Fixed Potential Errors:
Adjusted parameter handling and method calls to prevent crashes due to missing or invalid inputs.
Ensured that all audio processing objects are properly stopped and cleaned up when not in use.
Below is the updated code with explanations for each change:
def browse_audio_file(self):
file_path = filedialog.askopenfilename(filetypes=[("Audio Files", "*.wav;*.mp3"), ("All Files", "*.*")],
title="Select Audio File")
if file_path:
self.audio_file_path.set(file_path)
def on_tomatis_volume_change(self, val):
volume = float(val)
if self.tomatis_controller.source_sound is not None:
self.tomatis_controller.source_sound.mul = volume
def start_tomatis(self):
try:
settings = {
'audio_file': self.audio_file_path.get() if self.audio_file_path.get() else None,
'waveform': 'Sine', # Default waveform if no audio file is provided
'frequency': 440, # Default frequency if generating a waveform
'volume': float(self.tomatis_volume_scale.get()),
'min_freq': float(self.tomatis_min_freq_entry.get()),
'max_freq': float(self.tomatis_max_freq_entry.get()),
'switch_rate': float(self.tomatis_switch_rate_entry.get()),
'use_gate': self.tomatis_use_gate.get(),
'gate_speed': float(self.tomatis_gate_speed_entry.get()),
'use_reverb': self.tomatis_use_reverb.get()
}
self.tomatis_controller.start(settings)
except ValueError as e:
messagebox.showerror("Invalid Input", f"Invalid input: {e}")
def stop_tomatis(self):
self.tomatis_controller.stop()
Explanation of Changes:
Audio File Selection:
Added a text entry and "Browse" button for users to select an audio file.
The selected file path is stored in self.audio_file_path.
Controls for Dynamic Filtering and Gating:
Added inputs for Minimum Frequency, Maximum Frequency, and Filter Switch Rate.
Included checkboxes to enable/disable Gating and Reverb.
Added an input for Gate Speed to control the gating effect.
Volume Control:
Implemented a volume slider that adjusts the playback volume.
Start and Stop Buttons:
Buttons to initiate and stop the Tomatis Method processing.
Usage Instructions
Select an Audio File (Optional):
Click on "Browse" to select an audio file (e.g., a music track) to use as the source sound.
If no file is selected, a default waveform (sine wave) will be used.
Adjust Settings:
Set the Volume to control the overall playback level.
Specify Minimum Frequency and Maximum Frequency to define the range of the dynamic filter.
Set the Filter Switch Rate to control how fast the filter alternates between the two frequencies.
Enable Gating if desired and set the Gate Speed to adjust the rhythm of the gating effect.
Toggle Use Reverb to add ambient effects to the sound.
Start Processing:
Click "Start Tomatis" to begin processing the audio with the selected settings.
The audio will play with dynamic filtering and gating applied.
Stop Processing:
Click "Stop Tomatis" to stop the playback and processing.
Notes on the Tomatis Method Implementation
Dynamic Filtering:
Simulates the "Electronic Ear" by alternating the filter frequency between min_freq and max_freq.
Using a square wave LFO ensures sudden shifts between the two frequencies, aligning with the Tomatis approach.
Gating:
Modulates the amplitude of the sound to create rhythmic interruptions, which can enhance auditory processing according to the Tomatis Method.
Audio File Support:
Allowing users to select familiar or preferred audio enhances engagement and can produce better therapeutic outcomes.
Error Handling and Fixes
Input Validation:
Added try-except blocks to catch and display errors if invalid inputs are provided.
Ensured that numerical inputs are converted safely and errors are reported to the user.
Audio Object Management:
Made sure all audio processing objects are properly stopped to prevent errors when restarting or closing the application.
By incorporating these enhancements, the Tomatis sound generation in your script is now more innovative and better aligned with the actual principles of the Tomatis Method. The added features and improved error handling should provide a more robust and effective tool for users.