2016-12-06 1 views
1

참가자가 사운드 파일에서 2/30 사운드를들을 때만 입력 또는 스페이스 바를 얼마나 빨리 눌러야 하는지를 측정하는 스크립트를 만들고 싶습니다. 그래서 사용자는 아무 것도 누르지 않아도되고 스크립트는 계속해서 다음 소리 파일로 이동합니다. 어떻게해야합니까? 내가 지금있는 것은 이것이다 : (대신 사운드 파일, 나는 텍스트 기압 있습니다.) :Python 스크립트가 작동하지 않습니까? : 사운드 재생, 반응 시간 측정

# Grounding of Words Experiment # 

#Import libraries 
import re 
import glob 
from psychopy import sound, visual, event, data, core, gui # imports a module for visual presentation and one for controlling events like key presses 


# ID, age, gender box display 
myDlg = gui.Dlg(title="Experiment") #, pos=(400,400) 
myDlg.addField('ID:') 
myDlg.addField('Age:') 
myDlg.addField('Gender:', choices = ['Female', 'Male']) 
myDlg.show()#you have to call show() for a Dlg 
if myDlg.OK: 
    ID = myDlg.data[0] 
    Age = myDlg.data[1] 
    Gender = myDlg.data[2] 
else: 
    core.quit() 

trial=0 

#Creates the outfile, that will be the file containing our data, the name of the file, as saved on the computer is the filename 
out_file="Grounding_experiment_results.csv" 
#Creates the header for the data 
header="trial,ID,Gender,Age,Word,rt,SpaceKlik\n" 
#opens the outfile in writemode 
with open(out_file,"w") as f: 
    f.write(header)#writes the header in the outfile 


# define window 
win = visual.Window(fullscr=True) # defines a window using default values (= gray screen, fullscr=False, etc) 

# Instruction box display 

def instruct(txt): 
    instructions = visual.TextStim(win, text=txt, height = 0.05) # create an instruction text 
    instructions.draw() # draw the text stimulus in a "hidden screen" so that it is ready to be presented 
    win.flip() # flip the screen to reveal the stimulus 
    event.waitKeys() # wait for any key press 

instruct(''' 
Welcome to the experiment! 

You will be hearing different words. 
Whenever you hear the word "Klik" and "Kast" please press the left mouse button. 
Whenever you hear any other word - do nothing. 
Try to be as fast and accurate as possible. 
Please put on the headphones. 
The experiment will take 5 minutes. 

Press any key to start the experiment''') 

# Play sound 

# Function that makes up a trial 

trial(word): 
    global trial 
    trial += 1 
    if word in ["Klik", "Press", "Throw"]: 
     condition = "press" 
    else : 
     condition = "no_press" 
    event.clearEvents() 
    for frame in range(90): 
     text = visual.TextStim(win, text=word, height = 0.05) 
     text.draw() # draw the text stimulus in a "hidden screen" so that it is ready to be presented 
     time_start=win.flip() 
    try: 
     key, time_key=event.getKeys(keyList=['space', 'escape'], timeStamped = True)[0] # wait for any key press 
    except IndexError: 
     key = "0" 
     rt = "NA" 
    else: 
     if key=='escape': 
       core.quit() 
     rt = time_key - time_start 
    if key == "space" and condition=="press": 
     accuracy = 1 
    elif key == "0" and condition=="no_press": 
     accuracy = 1 
    else: 
     accuracy = 0 
    with open(out_file,"a") as f: 
     f.write("{},{},{},{},{},{},{},{}\n".format(trial,ID,Gender,Age,word,accuracy,rt,SpaceKlik)) 

# s = sound.Sound('sound.wav') 
# s.play() 

# Register space bar press or mouse click 

# Measure reaction time 

# Check to see if answer is correct to sound - certain sound files are "klik". Others "kast", "løb", "sko" and so on 

# Write csv logfile with coloumns: "ID", "Gender", "Word", "Correct/incorrect", "Reaction time", "Space/click" 

나는 모든 말에 PsychoPy에서 실행됩니다. 친절한 도움을 미리 주셔서 감사합니다.

+0

일반적인 팁으로 'trial'을 전역 변수로 사용하지 마십시오. 단순히'trial()'함수 밖에서 그것을 증가시키고 그것을 두번째 매개 변수로 함수에 전달하십시오. 마찬가지로 명령 함수를 실행할 때마다 텍스트 자극을 만들지 마십시오 (시간이 많이 소요되는 작업 임). 그것을 한 번 만들고 새 텍스트 내용과 함께 함수에 텍스트 자극을 전달하십시오. 이것은 텍스트 자극이 모든 프레임에서 다시 인스턴스화되는 평가판 기능에서 훨씬 더 큰 문제입니다. 이것은 매우 비효율적이며 타이밍 문제를 일으킬 수 있습니다. –

답변

0

들여 쓰기에 문제가있어 적절한 수준의 평가판 기능에서 모든 것이 실행되고 있지 않습니다. 응답 처리 여부를보다 직접적으로 확인하기 위해 예외 처리를 생략 할 수 있습니다. 그런 다음 루프가 완료되었지만 키를 누를 경우 발생하는 상황을 처리하기 위해 for 루프에 else: 절을 사용하십시오. 이렇게하면 주어진 프레임에서 발생하는 무응답의 논리를 처리하지 않아도됩니다. 응답이 곧 발생하면 아무 의미가 없습니다. 이 일반 의사와 같은

뭔가 :

# define window 
win = visual.Window(fullscr=True) 

# function to draw instructions (probably overkill unless run more than once) 
def instruct(instructions = 'xxx'): 
    # as you have above 

# function to run each trial 
def trial(number = -999, sound_name = 'A'): 

    sound = Sound.sound(sound_name) 

    if sound_name in ["Klik.wav", "Press.wav", "Throw.wav"]: 
     condition = "press" 
    else: 
     condition = "no_press" 

    event.clearEvents() 

    sound.play() 

    for frame in range(90): 

     time_start = win.flip() 

     keys = event.getKeys(keyList=['space', 'escape'], timeStamped = True) 
     if keys: # if a non-empty list returned: 
      key, time_key = keys[0] 
      rt = time_key - time_start 

      sound.stop() # ready to start next trial immediately 

      if key == 'escape': 
       core.quit() 

      if condition == "press": 
       return {'accuracy':1, 'rt':rt} 
      else: 
       return {'accuracy':0, 'rt':rt} 

    else: # the loop ended without a key press 
     if condition == "press": 
      return {'accuracy':0, 'rt':'NA'} 
     else: 
      return {'accuracy':1, 'rt':'NA'} 

#### 
# run the experiment: 
#### 

#### 
# show the instructions: 
#### 
instruct('some instructions') 

#### 
# run the trials: 
#### 
for trial_num in range(10): 

    # run each trial and get the results. 
    # I'm not sure where you're getting your sound values 
    # but they could be indexed from a list using the trial number: 
    result = trial(number=trial_num, sound_name=sound_names[trial_num]) 

    # then save the values from the returned dictionary to a file 
0

좋아는 좋은 - 감사합니다! 이제 스크립트를 계속 개발해 보았습니다. 평가판 목록을 추가했는데 지금은 무엇을해야할지 잘 모릅니다. 내 스크립트는 다음과 같습니다 :

# Grounding of Words Experiment # 

# -*- coding: utf-8 -*- 

#Import libraries 
import re 
import glob 
from psychopy import sound, visual, event, data, core, gui # imports a module for visual presentation and one for controlling events like key presses 
import ppc 

# ID, age, gender box display 
myDlg = gui.Dlg(title="Experiment") #, pos=(400,400) 
myDlg.addField('ID:') 
myDlg.addField('Age:') 
myDlg.addField('Gender:', choices = ['Female', 'Male']) 
myDlg.show()#you have to call show() for a Dlg 
if myDlg.OK: 
    ID = myDlg.data[0] 
    Age = myDlg.data[1] 
    Gender = myDlg.data[2] 
else: 
    core.quit() 

# define window 
win = visual.Window(fullscr=True) 


# function to draw instructions (probably overkill unless run more than once) 
def instruct(txt): 
    instructions = visual.TextStim(win, text=txt, height = 0.05) # create an instruction text 
    instructions.draw() # draw the text stimulus in a "hidden screen" so that it is ready to be presented 
    win.flip() # flip the screen to reveal the stimulus 
    event.waitKeys() # wait for any key press 
    # as you have above 


# function to run each trial 
def trial(number = -999, sound_name = 'A'): 

    sound = Sound.sound() 

    if sound_name in ["dog-howling.wav"]: 
     condition = "press" 
    else: 
     condition = "no_press" 

    event.clearEvents() 

    sound.play(sound_name) 

    for frame in range(90): 

     time_start = win.flip() 

     keys = event.getKeys(keyList=['space', 'escape'], timeStamped = True) 
     if keys: # if a non-empty list returned: 
      key, time_key = keys[0] 
      rt = time_key - time_start 

      sound.stop() # ready to start next trial immediately 

      if key == 'escape': 
       core.quit() 

      if condition == "press": 
       return {'accuracy':1, 'rt':rt} 
      else: 
       return {'accuracy':0, 'rt':rt} 

    else: # the loop ended without a key press 
     if condition == "press": 
      return {'accuracy':0, 'rt':'NA'} 
     else: 
      return {'accuracy':1, 'rt':'NA'} 
#### 
# define triallist 

trial_list = [] 
conditions = ["klik", "notklik"] 
sounds = ["dog-howling.wav", "sound2.wav", "sound3.wav"] 
for condition in conditions: 
    for sound in sounds: 
     # Add a dictionary for every trial 
      trial_list += [{ 
       'ID': ID, 
       'age': AGE, 
       'gender': GENDER, 
       'condition': condition, 
       'sounds': sound, 
       'rating': '', 
       'rt': '' 
        }] 

# Randomize order 
trial_list = sample(trial_list, len(trial_list)) 

# Add trial numbers 
for i, trial in enumerate(trial_list): 
    trial['no'] = i + 1 # start at 1 

# write file 

#### 
# run the experiment: 
#### 

#### 
# show the instructions: 
#### 
instruct('''Welcome to the experiment! 

You will be hearing different words. 
Whenever you hear the word "Klik" and "Kast" please press the left mouse button. 
Whenever you hear any other word - do nothing. 
Try to be as fast and accurate as possible. 
Please put on the headphones. 
The experiment will take 5 minutes. 

Press any key to start the experiment''') 

#### 
# run the trials: 
#### 
for trial_num in range(10): 

    # run each trial and get the results. 
    # I'm not sure where you're getting your sound values 
    # but they could be indexed from a list using the trial number: 
    result = trial(number=trial_num, sound_name=sound_names[trial_num]) 

    # then save the values from the returned dictionary to a file+ 

#Creates the outfile, that will be the file containing our data, the name of the file, as saved on the computer is the filename 
#out_file="Grounding_experiment_results.csv" 
#Creates the header for the data 
#header="trial,ID,Gender,Age,Word,rt,SpaceKlik\n" 
#opens the outfile in writemode 
#with open(out_file,"w") as f: 
# f.write(header)#writes the header in the outfile 
+0

당신은 실제로'TrialHandler' 클래스를 조사 할 필요가 있습니다. 평가판 목록을 보내면 평가판 번호를 추적하고 데이터를 저장하는 등의 작업을 자동으로 처리합니다. PsychoPy의 코더 뷰에있는 데모 메뉴에는 몇 가지 예가 있습니다. –

관련 문제