import numpy as np import sounddevice as sd from scipy import signal import…
- User
import numpy as np import sounddevice as sd from scipy import signal import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter as tk from tkinter import ttk, messagebox
class TomatisMethodController: def init(self, ax: plt.Axes, canvas: FigureCanvasTkAgg, root: tk.Tk): self.ax = ax self.canvas = canvas self.root = root self.is_playing = False self.left_freq = 200 self.right_freq = 800 self.left_q = 1.0 self.right_q = 1.0 self.left_volume = 0.3 self.right_volume = 0.3 self.stream = None self.sample_rate = 44100 self.buffer_size = 1024 self.noise_type = 'white'
self.update_filters() self.left_state = np.zeros(max(len(self.b_left_filter), len(self.a_left_filter)) - 1) self.right_state = np.zeros(max(len(self.b_right_filter), len(self.a_right_filter)) - 1) def update_filters(self): self.b_left_filter, self.a_left_filter = self.create_bandpass_filter(self.left_freq, self.left_q) self.b_right_filter, self.a_right_filter = self.create_bandpass_filter(self.right_freq, self.right_q) def create_bandpass_filter(self, freq, q): nyquist = 0.5 * self.sample_rate bandwidth = freq / q low = (freq - bandwidth / 2) / nyquist high = (freq + bandwidth / 2) / nyquist low = max(low, 0.001) high = min(high, 0.999) b, a = signal.butter(2, [low, high], btype='band') return b, a def generate_noise(self, num_frames): return np.random.normal(0, 1, num_frames) def generate_tomatis_sound(self, num_frames): left_noise = self.generate_noise(num_frames) right_noise = self.generate_noise(num_frames) left_filtered, self.left_state = signal.lfilter(self.b_left_filter, self.a_left_filter, left_noise, zi=self.left_state) right_filtered, self.right_state = signal.lfilter(self.b_right_filter, self.a_right_filter, right_noise, zi=self.right_state) left_output = left_filtered * self.left_volume right_output = right_filtered * self.right_volume return np.column_stack((left_output, right_output)) def audio_callback(self, outdata, frames, time_info, status): data = self.generate_tomatis_sound(frames) outdata[:] = data.astype(np.float32) def start(self): if not self.is_playing: self.stream = sd.OutputStream( channels=2, callback=self.audio_callback, samplerate=self.sample_rate, blocksize=self.buffer_size, dtype='float32' ) self.stream.start() self.is_playing = True self.update_plot() def stop(self): if self.is_playing and self.stream is not None: self.stream.stop() self.stream.close() self.stream = None self.is_playing = False self.ax.clear() self.canvas.draw() def update_settings(self): self.update_filters() if self.is_playing: self.update_plot() def update_plot(self): if self.is_playing: num_frames = self.buffer_size sound = self.generate_tomatis_sound(num_frames) t = np.linspace(0, num_frames / self.sample_rate, num_frames) self.ax.clear() self.ax.plot(t, sound[:, 0], label='Left', color='blue') self.ax.plot(t, sound[:, 1], label='Right', color='red') self.ax.set_title('Tomatis Waveforms') self.ax.set_xlabel('Time (s)') self.ax.set_ylabel('Amplitude') self.ax.legend() self.canvas.draw() self.root.after(100, self.update_plot)class Application(tk.Tk): def init(self): super().init() self.title("Tomatis Method Controller") self.geometry("800x600")
fig, ax = plt.subplots() canvas = FigureCanvasTkAgg(fig, self) canvas_widget = canvas.get_tk_widget() canvas_widget.pack(fill=tk.BOTH, expand=True) self.controller = TomatisMethodController(ax, canvas, self) settings_frame = ttk.LabelFrame(self, text="Settings") settings_frame.pack(fill="x", expand=True) # Frequency and Q-factor sliders ttk.Label(settings_frame, text="Left Frequency:").grid(row=0, column=0) self.left_freq_slider = ttk.Scale(settings_frame, from_=50, to=1000, orient='horizontal', command=self.update_frequency) self.left_freq_slider.set(self.controller.left_freq) self.left_freq_slider.grid(row=0, column=1) ttk.Label(settings_frame, text="Right Frequency:").grid(row=1, column=0) self.right_freq_slider = ttk.Scale(settings_frame, from_=50, to=1000, orient='horizontal', command=self.update_frequency) self.right_freq_slider.set(self.controller.right_freq) self.right_freq_slider.grid(row=1, column=1) ttk.Label(settings_frame, text="Left Q-Factor:").grid(row=2, column=0) self.left_q_slider = ttk.Scale(settings_frame, from_=0.1, to=10.0, orient='horizontal', command=self.update_q_factor) self.left_q_slider.set(self.controller.left_q) self.left_q_slider.grid(row=2, column=1) ttk.Label(settings_frame, text="Right Q-Factor:").grid(row=3, column=0) self.right_q_slider = ttk.Scale(settings_frame, from_=0.1, to=10.0, orient='horizontal', command=self.update_q_factor) self.right_q_slider.set(self.controller.right_q) self.right_q_slider.grid(row=3, column=1) # Volume sliders ttk.Label(settings_frame, text="Left Volume:").grid(row=4, column=0) self.left_volume_slider = ttk.Scale(settings_frame, from_=0, to=1, orient='horizontal', command=self.update_volume) self.left_volume_slider.set(self.controller.left_volume) self.left_volume_slider.grid(row=4, column=1) ttk.Label(settings_frame, text="Right Volume:").grid(row=5, column=0) self.right_volume_slider = ttk.Scale(settings_frame, from_=0, to=1, orient='horizontal', command=self.update_volume) self.right_volume_slider.set(self.controller.right_volume) self.right_volume_slider.grid(row=5, column=1) start_button = ttk.Button(self, text="Start", command=self.controller.start) start_button.pack(side=tk.BOTTOM, pady=5) stop_button = ttk.Button(self, text="Stop", command=self.controller.stop) stop_button.pack(side=tk.BOTTOM, pady=5) def update_frequency(self, _): self.controller.left_freq = self.left_freq_slider.get() self.controller.right_freq = self.right_freq_slider.get() self.controller.update_settings() def update_q_factor(self, _): self.controller.left_q = self.left_q_slider.get() self.controller.right_q = self.right_q_slider.get() self.controller.update_settings() def update_volume(self, _): self.controller.left_volume = self.left_volume_slider.get() self.controller.right_volume = self.right_volume_slider.get() self.controller.update_settings()if name == "main": app = Application() app.mainloop() улучши код - синтез частот более эффективный тренинг мозга через ухо, цель активация внимания и памяти
- Assistant
Certainly! I've improved your code to create a more effective auditory stimulation aimed at activating attention and memory. The updated code replaces the filtered noise with binaural beats, which are known to influence brainwave patterns and can enhance cognitive functions like attention and memory.
Key Improvements:
-
Binaural Beats Generation: Instead of using bandpass-filtered noise, the code now generates sine waves with slightly different frequencies for each ear. The difference between the frequencies (beat frequency) corresponds to brainwave frequencies associated with attention and memory (e.g., Beta and Gamma waves).
-
Adjustable Base and Beat Frequencies: Users can now adjust the base frequency and the desired beat frequency, providing control over the auditory stimulation to target specific cognitive states.
-
Presets for Cognitive Enhancement: Added buttons to quickly set frequencies that are commonly associated with increased attention and memory.
-
Enhanced GUI: Updated the GUI to reflect the new parameters and provide an intuitive interface for users to customize their experience.
Here's the improved code:
import numpy as np import sounddevice as sd import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter as tk from tkinter import ttk class TomatisMethodController: def __init__(self, ax: plt.Axes, canvas: FigureCanvasTkAgg, root: tk.Tk): self.ax = ax self.canvas = canvas self.root = root self.is_playing = False # Parameters for binaural beats self.base_freq = 440.0 # Base frequency in Hz self.beat_freq = 15.0 # Beat frequency in Hz (Beta wave range) self.volume = 0.5 self.sample_rate = 44100 self.buffer_size = 1024 self.time = np.arange(self.buffer_size) / self.sample_rate self.phase_left = 0.0 self.phase_right = 0.0 def generate_binaural_beats(self, num_frames): t = (np.arange(num_frames) + self.phase_left) / self.sample_rate left_tone = np.sin(2 * np.pi * self.base_freq * t) t = (np.arange(num_frames) + self.phase_right) / self.sample_rate right_tone = np.sin(2 * np.pi * (self.base_freq + self.beat_freq) * t) self.phase_left += num_frames self.phase_right += num_frames # Ensure the phase doesn't grow indefinitely self.phase_left %= self.sample_rate self.phase_right %= self.sample_rate # Combine left and right tones output = np.column_stack((left_tone, right_tone)) * self.volume return output.astype(np.float32) def audio_callback(self, outdata, frames, time_info, status): data = self.generate_binaural_beats(frames) outdata[:] = data def start(self): if not self.is_playing: self.stream = sd.OutputStream( channels=2, callback=self.audio_callback, samplerate=self.sample_rate, blocksize=self.buffer_size, dtype='float32' ) self.stream.start() self.is_playing = True self.update_plot() def stop(self): if self.is_playing and self.stream is not None: self.stream.stop() self.stream.close() self.stream = None self.is_playing = False self.ax.clear() self.canvas.draw() def update_settings(self): if self.is_playing: self.update_plot() def update_plot(self): if self.is_playing: num_frames = self.buffer_size sound = self.generate_binaural_beats(num_frames) t = np.linspace(0, num_frames / self.sample_rate, num_frames) self.ax.clear() self.ax.plot(t, sound[:, 0], label='Left', color='blue') self.ax.plot(t, sound[:, 1], label='Right', color='red') self.ax.set_title('Binaural Beats Waveforms') self.ax.set_xlabel('Time (s)') self.ax.set_ylabel('Amplitude') self.ax.legend() self.canvas.draw() self.root.after(100, self.update_plot) class Application(tk.Tk): def __init__(self): super().__init__() self.title("Cognitive Enhancement Audio") self.geometry("800x600") fig, ax = plt.subplots() canvas = FigureCanvasTkAgg(fig, self) canvas_widget = canvas.get_tk_widget() canvas_widget.pack(fill=tk.BOTH, expand=True) self.controller = TomatisMethodController(ax, canvas, self) settings_frame = ttk.LabelFrame(self, text="Settings") settings_frame.pack(fill="x", expand=True) # Base frequency slider ttk.Label(settings_frame, text="Base Frequency (Hz):").grid(row=0, column=0) self.base_freq_slider = ttk.Scale(settings_frame, from_=100, to=1000, orient='horizontal', command=self.update_frequencies) self.base_freq_slider.set(self.controller.base_freq) self.base_freq_slider.grid(row=0, column=1, padx=5, pady=5) # Beat frequency slider ttk.Label(settings_frame, text="Beat Frequency (Hz):").grid(row=1, column=0) self.beat_freq_slider = ttk.Scale(settings_frame, from_=0.1, to=40.0, orient='horizontal', command=self.update_frequencies) self.beat_freq_slider.set(self.controller.beat_freq) self.beat_freq_slider.grid(row=1, column=1, padx=5, pady=5) # Volume slider ttk.Label(settings_frame, text="Volume:").grid(row=2, column=0) self.volume_slider = ttk.Scale(settings_frame, from_=0, to=1, orient='horizontal', command=self.update_volume) self.volume_slider.set(self.controller.volume) self.volume_slider.grid(row=2, column=1, padx=5, pady=5) # Preset Buttons presets_frame = ttk.LabelFrame(self, text="Presets") presets_frame.pack(fill="x", expand=True) ttk.Button(presets_frame, text="Attention (Beta)", command=self.set_beta_preset).grid(row=0, column=0, padx=5, pady=5) ttk.Button(presets_frame, text="Memory (Gamma)", command=self.set_gamma_preset).grid(row=0, column=1, padx=5, pady=5) # Start and Stop buttons controls_frame = ttk.Frame(self) controls_frame.pack(fill="x", expand=True, pady=10) start_button = ttk.Button(controls_frame, text="Start", command=self.controller.start) start_button.pack(side=tk.LEFT, padx=5) stop_button = ttk.Button(controls_frame, text="Stop", command=self.controller.stop) stop_button.pack(side=tk.LEFT, padx=5) def update_frequencies(self, _): self.controller.base_freq = self.base_freq_slider.get() self.controller.beat_freq = self.beat_freq_slider.get() self.controller.update_settings() def update_volume(self, _): self.controller.volume = self.volume_slider.get() self.controller.update_settings() def set_beta_preset(self): # Beta waves (13-30 Hz) are associated with active thinking and focus self.beat_freq_slider.set(20.0) self.update_frequencies(None) def set_gamma_preset(self): # Gamma waves (30-100 Hz) are associated with memory and information processing self.beat_freq_slider.set(40.0) self.update_frequencies(None) if __name__ == "__main__": app = Application() app.mainloop()Explanation of Improvements:
-
Binaural Beats Generation:
- Replaced the
generate_noiseand bandpass filtering withgenerate_binaural_beats, which creates sine waves for left and right channels. - The left channel is a sine wave at the base frequency.
- The right channel is a sine wave at the base frequency plus the beat frequency.
- This creates an auditory illusion of a third tone (the binaural beat) at the beat frequency, which the brain perceives due to the frequency difference.
- Replaced the
-
Adjustable Frequencies:
- Added sliders to adjust the base frequency and beat frequency.
- Base frequency ranges from 100 Hz to 1000 Hz, allowing users to select comfortable and effective tones.
- Beat frequency ranges from 0.1 Hz to 40 Hz, covering Delta to low Gamma brainwave frequencies.
-
Volume Control:
- A volume slider allows users to adjust the playback volume for comfort.
-
Presets for Cognitive States:
- Added buttons to quickly set beat frequencies associated with increased attention (Beta waves) and memory enhancement (Gamma waves).
- Beta preset sets the beat frequency to 20 Hz.
- Gamma preset sets the beat frequency to 40 Hz.
-
Improved GUI Layout:
- Organized controls into frames for settings and presets.
- Labeled sliders and buttons for clarity.
- Updated plot titles and labels to reflect the binaural beats.
How to Use the Improved Application:
-
Adjust Base Frequency:
- Use the "Base Frequency" slider to set the main tone frequency (e.g., 440 Hz).
- This is the frequency of the sine wave played in the left ear.
-
Adjust Beat Frequency:
- Use the "Beat Frequency" slider to set the difference between the left and right frequencies.
- A beat frequency in the Beta range (13-30 Hz) is suitable for enhancing attention.
- A beat frequency in the Gamma range (30-50 Hz) can aid in memory activation.
-
Set Volume:
- Adjust the "Volume" slider for a comfortable listening level.
-
Use Presets:
- Click the "Attention (Beta)" button to automatically set the beat frequency to 20 Hz.
- Click the "Memory (Gamma)" button to set the beat frequency to 40 Hz.
-
Start and Stop Audio:
- Click "Start" to begin playback and visualization.
- Click "Stop" to end the session.
Important Notes:
- Safety First: Always listen at a comfortable volume to avoid hearing damage.
- Individual Variability: The effectiveness of binaural beats can vary between individuals. Feel free to experiment with different frequencies to find what works best for you.
- Not a Medical Device: This application is intended for recreational use and is not a substitute for professional medical advice or treatment.
Dependencies:
Make sure you have the required Python packages installed:
pip install numpy sounddevice matplotlibDisclaimer:
This application is for educational and entertainment purposes. While some studies suggest potential benefits of binaural beats, scientific consensus on their efficacy is not established. Use responsibly.
I hope this improved code meets your needs for a more effective auditory brain training tool. Let me know if you have any questions or need further assistance!
-