Desafie sua memória! Jogue o novo jogo N-Back no aplicativo Emotiv

  • Desafie sua memória! Jogue o novo jogo N-Back no aplicativo Emotiv

    Desafie sua memória! Jogue o novo jogo N-Back no aplicativo Emotiv

Camada de Transmissão de Laboratório (LSL) para sincronizar múltiplos fluxos de dados

Roshini Randeniya

1 de out. de 2025

Compartilhar:

por Roshini Randeniya e Lucas Kleine

Operação:
Uma vez executado na linha de comando, este script inicia imediatamente um fluxo LSL. Sempre que a tecla 'Enter' é pressionada, ele envia um gatilho e toca um arquivo de áudio."""

import sounddevice as sd
import soundfile as sf
from pylsl import StreamInfo, StreamOutlet

def wait_for_keypress():
print("Pressione ENTER para iniciar a reprodução de áudio e enviar um marcador LSL.")

while True: # This loop waits for a keyboard input
    input_str = input()  # Wait for input from the terminal
    if input_str == "":  # If the enter key is pressed, proceed
        break

def AudioMarker(audio_file, outlet): # função para tocar áudio e enviar marcador
data, fs = sf.read(audio_file) # Carregar o arquivo de áudio

print("Playing audio and sending LSL marker...")
marker_val = [1]
outlet.push_sample(marker_val) # Send marker indicating the start of audio playback
sd.play(data, fs) # play the audio
sd.wait()  # Wait until audio is done playing
print("Audio playback finished.")

if name == "main": # LOOP PRINCIPAL
# Configurar fluxo LSL para marcadores
stream_name = 'AudioMarkers'
stream_type = 'Markers'
n_chans = 1
sr = 0 # Definir taxa de amostragem como 0 porque marcadores são irregulares
chan_format = 'int32'
marker_id = 'uniqueMarkerID12345'

info = StreamInfo(stream_name, stream_type, n_chans, sr, chan_format, marker_id)
outlet = StreamOutlet(info) # create LSL outlet

# Keep the script running and wait for ENTER key to play audio and send marker
while True:
    wait_for_keypress()
    audio_filepath = "/path/to/your/audio_file.wav"  # replace with correct path to your audio file
    AudioMarker(audio_filepath, outlet)
    # After playing audio and sending a marker, the script goes back to waiting for the next keypress</code></pre><p><em><strong>**By running this file (even before playing the audio), you've initiated an LSL stream through an outlet</strong></em><strong>. Now we'll view that stream in LabRecorder</strong></p><p><strong>STEP 5 - Use LabRecorder to view and save all LSL streams</strong></p><ol><li data-preset-tag="p"><p>Open LabRecorder</p></li><li data-preset-tag="p"><p>Press <em><strong>Update</strong></em>. The available LSL streams should be visible in the stream list<br> • You should be able to see streams from both EmotivPROs (usually called "EmotivDataStream") and the marker stream (called "AudioMarkers")</p></li><li data-preset-tag="p"><p>Click <em><strong>Browse</strong></em> to select a location to store data (and set other parameters)</p></li><li data-preset-tag="p"><p>Select all streams and press <em><strong>Record</strong></em> to start recording</p></li><li data-preset-tag="p"><p>Click Stop when you want to end the recording</p></li></ol><p><br></p><img alt="" src="https://framerusercontent.com/images/HFGuJF9ErVu2Jxrgtqt11tl0No.jpg"><h2><strong>Working with the data</strong></h2><p><strong>LabRecorder outputs an XDF file (Extensible Data Format) that contains data from all the streams. XDF files are structured into, </strong><em><strong>streams</strong></em><strong>, each with a different </strong><em><strong>header</strong></em><strong> that describes what it contains (device name, data type, sampling rate, channels, and more). You can use the below codeblock to open your XDF file and display some basic information.</strong></p><pre data-language="JSX"><code>

Este script de exemplo demonstra algumas funções básicas para importar e anotar dados de EEG coletados do software EmotivPRO. Ele usa MNE para carregar um arquivo XDF, imprimir alguns metadados básicos, criar um objeto info e plotar o espectro de potência."""

import pyxdf
import mne
import matplotlib.pyplot as plt
import numpy as np

Caminho para seu arquivo XDF

data_path = '/path/to/your/xdf_file.xdf'

Carregar o arquivo XDF

streams, fileheader = pyxdf.load_xdf(data_path)
print("Cabeçalho do Arquivo XDF:", fileheader)
print("Número de fluxos encontrados:", len(streams))

for i, stream in enumerate(streams):
print("\nFluxo", i + 1)
print("Nome do Fluxo:", stream['info']['name'][0])
print("Tipo de Fluxo:", stream['info']['type'][0])
print("Número de Canais:", stream['info']['channel_count'][0])
sfreq = float(stream['info']['nominal_srate'][0])
print("Taxa de Amostragem:", sfreq)
print("Número de Amostras:", len(stream['time_series']))
print("Imprimir os primeiros 5 pontos de dados:", stream['time_series'][:5])

channel_names = [chan['label'][0] for chan in stream['info']['desc'][0]['channels'][0]['channel']]
print("Channel Names:", channel_names)
channel_types = 'eeg'
Criar objeto de informações MNE

info = mne.create_info(channel_names, sfreq, channel_types)
data = np.array(stream['time_series']).T # Os dados precisam ser transpostos: canais x amostras
raw = mne.io.RawArray(data, info)
raw.plot_psd(fmax=50) # plotar um espectrograma simples (densidade espectral de potência)Recursos adicionaisBaixe este tutorial como um notebook Jupyter do GitHub da EMOTIVConfira a documentação online do LSL, incluindo o arquivo README oficial no GitHubVocê precisará de um ou mais dispositivos de aquisição de dados compatíveis para coletar dadosTodos os dispositivos de brainware da EMOTIV se conectam ao software EmotivPRO, que possui recursos LSL integrados para enviar e receber fluxos de dadosRecursos adicionais:Código para executar LSL usando os dispositivos da Emotiv, com scripts de exemploDemonstrativo de LSL útil no YouTubeRepositório do GitHub SCCN LSL para todas as bibliotecas associadasRepositório do GitHub para uma coleção de submódulos e aplicativosPipeline de análise HyPyP para estudos de Hiperscaneamento

por Roshini Randeniya e Lucas Kleine

Operação:
Uma vez executado na linha de comando, este script inicia imediatamente um fluxo LSL. Sempre que a tecla 'Enter' é pressionada, ele envia um gatilho e toca um arquivo de áudio."""

import sounddevice as sd
import soundfile as sf
from pylsl import StreamInfo, StreamOutlet

def wait_for_keypress():
print("Pressione ENTER para iniciar a reprodução de áudio e enviar um marcador LSL.")

while True: # This loop waits for a keyboard input
    input_str = input()  # Wait for input from the terminal
    if input_str == "":  # If the enter key is pressed, proceed
        break

def AudioMarker(audio_file, outlet): # função para tocar áudio e enviar marcador
data, fs = sf.read(audio_file) # Carregar o arquivo de áudio

print("Playing audio and sending LSL marker...")
marker_val = [1]
outlet.push_sample(marker_val) # Send marker indicating the start of audio playback
sd.play(data, fs) # play the audio
sd.wait()  # Wait until audio is done playing
print("Audio playback finished.")

if name == "main": # LOOP PRINCIPAL
# Configurar fluxo LSL para marcadores
stream_name = 'AudioMarkers'
stream_type = 'Markers'
n_chans = 1
sr = 0 # Definir taxa de amostragem como 0 porque marcadores são irregulares
chan_format = 'int32'
marker_id = 'uniqueMarkerID12345'

info = StreamInfo(stream_name, stream_type, n_chans, sr, chan_format, marker_id)
outlet = StreamOutlet(info) # create LSL outlet

# Keep the script running and wait for ENTER key to play audio and send marker
while True:
    wait_for_keypress()
    audio_filepath = "/path/to/your/audio_file.wav"  # replace with correct path to your audio file
    AudioMarker(audio_filepath, outlet)
    # After playing audio and sending a marker, the script goes back to waiting for the next keypress</code></pre><p><em><strong>**By running this file (even before playing the audio), you've initiated an LSL stream through an outlet</strong></em><strong>. Now we'll view that stream in LabRecorder</strong></p><p><strong>STEP 5 - Use LabRecorder to view and save all LSL streams</strong></p><ol><li data-preset-tag="p"><p>Open LabRecorder</p></li><li data-preset-tag="p"><p>Press <em><strong>Update</strong></em>. The available LSL streams should be visible in the stream list<br> • You should be able to see streams from both EmotivPROs (usually called "EmotivDataStream") and the marker stream (called "AudioMarkers")</p></li><li data-preset-tag="p"><p>Click <em><strong>Browse</strong></em> to select a location to store data (and set other parameters)</p></li><li data-preset-tag="p"><p>Select all streams and press <em><strong>Record</strong></em> to start recording</p></li><li data-preset-tag="p"><p>Click Stop when you want to end the recording</p></li></ol><p><br></p><img alt="" src="https://framerusercontent.com/images/HFGuJF9ErVu2Jxrgtqt11tl0No.jpg"><h2><strong>Working with the data</strong></h2><p><strong>LabRecorder outputs an XDF file (Extensible Data Format) that contains data from all the streams. XDF files are structured into, </strong><em><strong>streams</strong></em><strong>, each with a different </strong><em><strong>header</strong></em><strong> that describes what it contains (device name, data type, sampling rate, channels, and more). You can use the below codeblock to open your XDF file and display some basic information.</strong></p><pre data-language="JSX"><code>

Este script de exemplo demonstra algumas funções básicas para importar e anotar dados de EEG coletados do software EmotivPRO. Ele usa MNE para carregar um arquivo XDF, imprimir alguns metadados básicos, criar um objeto info e plotar o espectro de potência."""

import pyxdf
import mne
import matplotlib.pyplot as plt
import numpy as np

Caminho para seu arquivo XDF

data_path = '/path/to/your/xdf_file.xdf'

Carregar o arquivo XDF

streams, fileheader = pyxdf.load_xdf(data_path)
print("Cabeçalho do Arquivo XDF:", fileheader)
print("Número de fluxos encontrados:", len(streams))

for i, stream in enumerate(streams):
print("\nFluxo", i + 1)
print("Nome do Fluxo:", stream['info']['name'][0])
print("Tipo de Fluxo:", stream['info']['type'][0])
print("Número de Canais:", stream['info']['channel_count'][0])
sfreq = float(stream['info']['nominal_srate'][0])
print("Taxa de Amostragem:", sfreq)
print("Número de Amostras:", len(stream['time_series']))
print("Imprimir os primeiros 5 pontos de dados:", stream['time_series'][:5])

channel_names = [chan['label'][0] for chan in stream['info']['desc'][0]['channels'][0]['channel']]
print("Channel Names:", channel_names)
channel_types = 'eeg'
Criar objeto de informações MNE

info = mne.create_info(channel_names, sfreq, channel_types)
data = np.array(stream['time_series']).T # Os dados precisam ser transpostos: canais x amostras
raw = mne.io.RawArray(data, info)
raw.plot_psd(fmax=50) # plotar um espectrograma simples (densidade espectral de potência)Recursos adicionaisBaixe este tutorial como um notebook Jupyter do GitHub da EMOTIVConfira a documentação online do LSL, incluindo o arquivo README oficial no GitHubVocê precisará de um ou mais dispositivos de aquisição de dados compatíveis para coletar dadosTodos os dispositivos de brainware da EMOTIV se conectam ao software EmotivPRO, que possui recursos LSL integrados para enviar e receber fluxos de dadosRecursos adicionais:Código para executar LSL usando os dispositivos da Emotiv, com scripts de exemploDemonstrativo de LSL útil no YouTubeRepositório do GitHub SCCN LSL para todas as bibliotecas associadasRepositório do GitHub para uma coleção de submódulos e aplicativosPipeline de análise HyPyP para estudos de Hiperscaneamento

por Roshini Randeniya e Lucas Kleine

Operação:
Uma vez executado na linha de comando, este script inicia imediatamente um fluxo LSL. Sempre que a tecla 'Enter' é pressionada, ele envia um gatilho e toca um arquivo de áudio."""

import sounddevice as sd
import soundfile as sf
from pylsl import StreamInfo, StreamOutlet

def wait_for_keypress():
print("Pressione ENTER para iniciar a reprodução de áudio e enviar um marcador LSL.")

while True: # This loop waits for a keyboard input
    input_str = input()  # Wait for input from the terminal
    if input_str == "":  # If the enter key is pressed, proceed
        break

def AudioMarker(audio_file, outlet): # função para tocar áudio e enviar marcador
data, fs = sf.read(audio_file) # Carregar o arquivo de áudio

print("Playing audio and sending LSL marker...")
marker_val = [1]
outlet.push_sample(marker_val) # Send marker indicating the start of audio playback
sd.play(data, fs) # play the audio
sd.wait()  # Wait until audio is done playing
print("Audio playback finished.")

if name == "main": # LOOP PRINCIPAL
# Configurar fluxo LSL para marcadores
stream_name = 'AudioMarkers'
stream_type = 'Markers'
n_chans = 1
sr = 0 # Definir taxa de amostragem como 0 porque marcadores são irregulares
chan_format = 'int32'
marker_id = 'uniqueMarkerID12345'

info = StreamInfo(stream_name, stream_type, n_chans, sr, chan_format, marker_id)
outlet = StreamOutlet(info) # create LSL outlet

# Keep the script running and wait for ENTER key to play audio and send marker
while True:
    wait_for_keypress()
    audio_filepath = "/path/to/your/audio_file.wav"  # replace with correct path to your audio file
    AudioMarker(audio_filepath, outlet)
    # After playing audio and sending a marker, the script goes back to waiting for the next keypress</code></pre><p><em><strong>**By running this file (even before playing the audio), you've initiated an LSL stream through an outlet</strong></em><strong>. Now we'll view that stream in LabRecorder</strong></p><p><strong>STEP 5 - Use LabRecorder to view and save all LSL streams</strong></p><ol><li data-preset-tag="p"><p>Open LabRecorder</p></li><li data-preset-tag="p"><p>Press <em><strong>Update</strong></em>. The available LSL streams should be visible in the stream list<br> • You should be able to see streams from both EmotivPROs (usually called "EmotivDataStream") and the marker stream (called "AudioMarkers")</p></li><li data-preset-tag="p"><p>Click <em><strong>Browse</strong></em> to select a location to store data (and set other parameters)</p></li><li data-preset-tag="p"><p>Select all streams and press <em><strong>Record</strong></em> to start recording</p></li><li data-preset-tag="p"><p>Click Stop when you want to end the recording</p></li></ol><p><br></p><img alt="" src="https://framerusercontent.com/images/HFGuJF9ErVu2Jxrgtqt11tl0No.jpg"><h2><strong>Working with the data</strong></h2><p><strong>LabRecorder outputs an XDF file (Extensible Data Format) that contains data from all the streams. XDF files are structured into, </strong><em><strong>streams</strong></em><strong>, each with a different </strong><em><strong>header</strong></em><strong> that describes what it contains (device name, data type, sampling rate, channels, and more). You can use the below codeblock to open your XDF file and display some basic information.</strong></p><pre data-language="JSX"><code>

Este script de exemplo demonstra algumas funções básicas para importar e anotar dados de EEG coletados do software EmotivPRO. Ele usa MNE para carregar um arquivo XDF, imprimir alguns metadados básicos, criar um objeto info e plotar o espectro de potência."""

import pyxdf
import mne
import matplotlib.pyplot as plt
import numpy as np

Caminho para seu arquivo XDF

data_path = '/path/to/your/xdf_file.xdf'

Carregar o arquivo XDF

streams, fileheader = pyxdf.load_xdf(data_path)
print("Cabeçalho do Arquivo XDF:", fileheader)
print("Número de fluxos encontrados:", len(streams))

for i, stream in enumerate(streams):
print("\nFluxo", i + 1)
print("Nome do Fluxo:", stream['info']['name'][0])
print("Tipo de Fluxo:", stream['info']['type'][0])
print("Número de Canais:", stream['info']['channel_count'][0])
sfreq = float(stream['info']['nominal_srate'][0])
print("Taxa de Amostragem:", sfreq)
print("Número de Amostras:", len(stream['time_series']))
print("Imprimir os primeiros 5 pontos de dados:", stream['time_series'][:5])

channel_names = [chan['label'][0] for chan in stream['info']['desc'][0]['channels'][0]['channel']]
print("Channel Names:", channel_names)
channel_types = 'eeg'
Criar objeto de informações MNE

info = mne.create_info(channel_names, sfreq, channel_types)
data = np.array(stream['time_series']).T # Os dados precisam ser transpostos: canais x amostras
raw = mne.io.RawArray(data, info)
raw.plot_psd(fmax=50) # plotar um espectrograma simples (densidade espectral de potência)Recursos adicionaisBaixe este tutorial como um notebook Jupyter do GitHub da EMOTIVConfira a documentação online do LSL, incluindo o arquivo README oficial no GitHubVocê precisará de um ou mais dispositivos de aquisição de dados compatíveis para coletar dadosTodos os dispositivos de brainware da EMOTIV se conectam ao software EmotivPRO, que possui recursos LSL integrados para enviar e receber fluxos de dadosRecursos adicionais:Código para executar LSL usando os dispositivos da Emotiv, com scripts de exemploDemonstrativo de LSL útil no YouTubeRepositório do GitHub SCCN LSL para todas as bibliotecas associadasRepositório do GitHub para uma coleção de submódulos e aplicativosPipeline de análise HyPyP para estudos de Hiperscaneamento

Continue lendo

Noções básicas de Oscilações Neurais