Unknown error with Stimuli - Movie

Traceback (most recent call last):
File “C:\Users\yx21446\AppData\Local\Programs\Python\Python310\lib\site-packages\psychopy\app\builder\builder.py”, line 2462, in onClick
dlg = Dlg(frame=self.parent.frame,
File "C:\Users\yx21446\AppData\Local\Programs\Python\Python310\lib\site-packages\psychopy\app\builder\dialogs_init
.py", line 1784, in init
BaseParamsDlg.init(self, frame=frame, element=element, experiment=experiment,
File "C:\Users\yx21446\AppData\Local\Programs\Python\Python310\lib\site-packages\psychopy\app\builder\dialogs_init
.py", line 824, in init
self.ctrls = ParamNotebook(self, element, experiment)
File “C:\Users\yx21446\AppData\Local\Programs\Python\Python310\lib\site-packages\psychopy\app\builder\dialogs_init_.py”, line 675, in init
page = self.CategoryPage(self, self.parent, params)
File “C:\Users\yx21446\AppData\Local\Programs\Python\Python310\lib\site-packages\psychopy\app\builder\dialogs_init_.py”, line 516, in init
self.addParam(“name”, param)
File “C:\Users\yx21446\AppData\Local\Programs\Python\Python310\lib\site-packages\psychopy\app\builder\dialogs_init_.py”, line 541, in addParam
self.ctrls[name] = ParamCtrls(self.dlg, param.label, param, self, name)
File “C:\Users\yx21446\AppData\Local\Programs\Python\Python310\lib\site-packages\psychopy\app\builder\dialogs_init_.py”, line 120, in init
fieldName=fieldName, size=wx.Size(self.valueWidth, 24))
TypeError: Size(): arguments did not match any overloaded call:
overload 1: too many arguments
overload 2: argument 1 has unexpected type ‘float’
overload 3: argument 1 has unexpected type ‘float’

Hello,
This is not possible to help you without seeing the relevant code/components.
Can you please elaborate on the problem and give us some context?

Thanks,
Chen

Hi Chen, thanks for the quick reply and please keep in mind that I started coding two days ago :smiley: In my experiment, I need to concatenate 13 videos - one longer video within which there will be 12 shorter ones (my stimuli). I was trying to code exactly this. When I opened the builder again and clicked on “movie”, this message popped up and asked to report to the developers - which I did.
Thanks a lot for your help!

Hey,
Are you looking for a way to solve it?
If so, please include your code :slight_smile:

Chen

Hi Chen, yes 100% :smiley: I need for my experiment. I will post the entire code once I will have found my way through :slight_smile:

Hey Chen, so I was able to put the video correctly in, including instructions and welcome message plus a fixation cross. Now I need to insert a second video which will be played 120 seconds after the first video, the second video will play for 20 seconds, and the back to the original video. Any idea on how to insert such second movie?
This is the code
#!/usr/bin/env python

-- coding: utf-8 --

“”"
This experiment was created using PsychoPy3 Experiment Builder (v2023.1.3),
on July 20, 2023, at 11:50
If you publish work using this script the most relevant publication is:

Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Lindeløv JK. (2019) 
    PsychoPy2: Experiments in behavior made easy Behav Res 51: 195. 
    https://doi.org/10.3758/s13428-018-01193-y

“”"

— Import packages —

from psychopy import locale_setup
from psychopy import prefs
from psychopy import plugins
plugins.activatePlugins()
prefs.hardware[‘audioLib’] = ‘ptb’
prefs.hardware[‘audioLatencyMode’] = ‘3’
from psychopy import sound, gui, visual, core, data, event, logging, clock, colors, layout
from psychopy.tools import environmenttools
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)

import numpy as np # whole numpy lib is available, prepend ‘np.’
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle, choice as randchoice
import os # handy system and path functions
import sys # to get file system encoding

import psychopy.iohub as io
from psychopy.hardware import keyboard

Ensure that relative paths start from the same directory as this script

_thisDir = os.path.dirname(os.path.abspath(file))
os.chdir(_thisDir)

Store info about the experiment session

psychopyVersion = ‘2023.1.3’
expName = ‘testvideo’ # from the Builder filename that created this script
expInfo = {
‘participant’: f"{randint(0, 999999):06.0f}",
‘session’: ‘001’,
}

— Show participant info dialog –

dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo[‘date’] = data.getDateStr() # add a simple timestamp
expInfo[‘expName’] = expName
expInfo[‘psychopyVersion’] = psychopyVersion

Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc

filename = thisDir + os.sep + u’data/%s%s_%s’ % (expInfo[‘participant’], expName, expInfo[‘date’])

An ExperimentHandler isn’t essential but helps with data saving

thisExp = data.ExperimentHandler(name=expName, version=‘’,
extraInfo=expInfo, runtimeInfo=None,
originPath=‘C:\Users\yx21446\OneDrive - University of Bristol\Desktop\Psychopy\testvideo.py’,
savePickle=True, saveWideText=True,
dataFileName=filename)

save a log file for detail verbose info

logFile = logging.LogFile(filename+‘.log’, level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file

endExpNow = False # flag for ‘escape’ or other condition => quit the exp
frameTolerance = 0.001 # how close to onset before ‘same’ frame

Start Code - component code to be run after the window creation

— Setup the Window —

win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType=‘pyglet’, allowStencil=False,
monitor=‘testMonitor’, color=[-1,-1,-1], colorSpace=‘rgb’,
backgroundImage=‘’, backgroundFit=‘none’,
blendMode=‘avg’, useFBO=True,
units=‘height’)
win.mouseVisible = False

Add a welcome message

welcome_message = visual.TextStim(
win=win, text=“Welcome and thank you for participating in this experiment.\n\n”
“During this experiment, you will be watching an episode of 'I’m a celebrity…get me out of here!, which will include eight commercial breaks. \n\nIf at any point you feel uncomfortable, you have the option to leave the experiment. Simply raise your hand, and the experiment will be stopped for you.”,
pos=(0, 0), color=‘white’, height=0.04)

Add an instructions message

instructions_message = visual.TextStim(
win=win, text=“The experiment is about to begin, please sit back, relax, and enjoy the show :)\n\n”
“Please find a comfortable seating position, relax, and enjoy the TV show. It’s important to minimize movement as much as possible, as any movement could potentially introduce significant noise into the data.\n\n”
“Please note that there will be a 90-second time interval before the experiment starts. This period is designed to record your baseline data.”,

pos=(0, 0), color='white', height=0.04)

Add a fixation cross

fixation_cross = visual.TextStim(
win=win, text=“+”,
pos=(0, 0), color=‘white’, height=0.05)

store frame rate of monitor if we can measure it

expInfo[‘frameRate’] = win.getActualFrameRate()
if expInfo[‘frameRate’] != None:
frameDur = 1.0 / round(expInfo[‘frameRate’])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess

— Setup input devices —

ioConfig = {}

Setup iohub keyboard

ioConfig[‘Keyboard’] = dict(use_keymap=‘psychopy’)

ioSession = ‘1’
if ‘session’ in expInfo:
ioSession = str(expInfo[‘session’])
ioServer = io.launchHubServer(window=win, **ioConfig)
eyetracker = None

create a default keyboard (e.g. to check for escape)

defaultKeyboard = keyboard.Keyboard(backend=‘iohub’)

— Initialize components for Routine “trial” —

movie = visual.MovieStim(
win, name=‘movie’,
filename=‘C:/Users/yx21446/OneDrive - University of Bristol/Desktop/PhD stimuli/1A.mp4’, movieLib=‘ffpyplayer’,
loop=False, volume=1.0, noAudio=False,
pos=(0, 0), size=(2.5, 2.5), units=win.units,
ori=0.0, anchor=‘center’,opacity=None, contrast=1.0,
depth=0
)

Create some handy timers

globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.Clock() # to track time remaining of each (possibly non-slip) routine

— Prepare to start Routine “trial” —

continueRoutine = True

Show the welcome message for 10 seconds or until a key is pressed

welcome_message.setAutoDraw(True)
timer = core.CountdownTimer(10.0) # 10 seconds countdown
while continueRoutine and timer.getTime() > 0:
win.flip()
if event.getKeys(): # Check for any key press to skip the message
break
welcome_message.setAutoDraw(False) # Hide the welcome message

Show the instructions message for 10 seconds or until a key is pressed

instructions_message.setAutoDraw(True)
timer = core.CountdownTimer(10.0) # 10 seconds countdown
while continueRoutine and timer.getTime() > 0:
win.flip()
if event.getKeys(): # Check for any key press to skip the message
break
instructions_message.setAutoDraw(False) # Hide the instructions message

Show the fixation cross for 10 seconds

fixation_cross.setAutoDraw(True)
timer = core.CountdownTimer(10.0) # 10 seconds countdown
while continueRoutine and timer.getTime() > 0:
win.flip()

fixation_cross.setAutoDraw(False) # Hide the fixation cross before starting the video

instructions_message.setAutoDraw(False) # Hide the instructions message before starting the video

update component parameters for each repeat

keep track of which components have finished

trialComponents = [movie]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, ‘status’):
thisComponent.status = NOT_STARTED

reset timers

t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock=“now”)
frameN = -1

— Run Routine “trial” —

routineForceEnded = not continueRoutine
while continueRoutine and routineTimer.getTime() < 60.0:
# get current time
t = routineTimer.getTime()
tThisFlip = win.getFutureFlipTime(clock=routineTimer)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *movie* updates

# if movie is starting this frame...
if movie.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
    # keep track of start time/frame for later
    movie.frameNStart = frameN  # exact frame index
    movie.tStart = t  # local t and not account for scr refresh
    movie.tStartRefresh = tThisFlipGlobal  # on global time
    win.timeOnFlip(movie, 'tStartRefresh')  # time at next scr refresh
    # add timestamp to datafile
    thisExp.timestampOnFlip(win, 'movie.started')
    # update status
    movie.status = STARTED
    movie.setAutoDraw(True)
    movie.play()

# if movie is stopping this frame...
if movie.status == STARTED:
    # is it time to stop? (based on global clock, using actual start)
    if tThisFlipGlobal > movie.tStartRefresh + 60-frameTolerance:
        # keep track of stop time/frame for later
        movie.tStop = t  # not accounting for scr refresh
        movie.frameNStop = frameN  # exact frame index
        # add timestamp to datafile
        thisExp.timestampOnFlip(win, 'movie.stopped')
        # update status
        movie.status = FINISHED
        movie.setAutoDraw(False)
        movie.stop()

# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
    core.quit()
    if eyetracker:
        eyetracker.setConnectionState(False)

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
    routineForceEnded = True
    break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in trialComponents:
    if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
        continueRoutine = True
        break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
    win.flip()

— Ending Routine “trial” —

for thisComponent in trialComponents:
if hasattr(thisComponent, “setAutoDraw”):
thisComponent.setAutoDraw(False)
movie.stop()

using non-slip timing so subtract the expected duration of this Routine (unless ended on request)

if routineForceEnded:
routineTimer.reset()
else:
routineTimer.addTime(-60.000000)

— End experiment —

Flip one final time so any remaining win.callOnFlip()

and win.timeOnFlip() tasks get executed before quitting

win.flip()

these shouldn’t be strictly necessary (should auto-save)

thisExp.saveAsWideText(filename+‘.csv’, delim=‘auto’)
thisExp.saveAsPickle(filename)
logging.flush()

Hey Chen, I need to insert a second video that will be played automatically 180 seconds after the first one, will be played for 20 seconds, and then back to the original video. Any idea on how to do it?
“”"

— Import packages —

from psychopy import locale_setup
from psychopy import prefs
from psychopy import plugins
plugins.activatePlugins()
prefs.hardware[‘audioLib’] = ‘ptb’
prefs.hardware[‘audioLatencyMode’] = ‘3’
from psychopy import sound, gui, visual, core, data, event, logging, clock, colors, layout
from psychopy.tools import environmenttools
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)

import numpy as np # whole numpy lib is available, prepend ‘np.’
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle, choice as randchoice
import os # handy system and path functions
import sys # to get file system encoding

import psychopy.iohub as io
from psychopy.hardware import keyboard

Ensure that relative paths start from the same directory as this script

_thisDir = os.path.dirname(os.path.abspath(file))
os.chdir(_thisDir)

Store info about the experiment session

psychopyVersion = ‘2023.1.3’
expName = ‘testvideo’ # from the Builder filename that created this script
expInfo = {
‘participant’: f"{randint(0, 999999):06.0f}",
‘session’: ‘001’,
}

— Show participant info dialog –

dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo[‘date’] = data.getDateStr() # add a simple timestamp
expInfo[‘expName’] = expName
expInfo[‘psychopyVersion’] = psychopyVersion

Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc

filename = thisDir + os.sep + u’data/%s%s_%s’ % (expInfo[‘participant’], expName, expInfo[‘date’])

An ExperimentHandler isn’t essential but helps with data saving

thisExp = data.ExperimentHandler(name=expName, version=‘’,
extraInfo=expInfo, runtimeInfo=None,
originPath=‘C:\Users\yx21446\OneDrive - University of Bristol\Desktop\Psychopy\testvideo.py’,
savePickle=True, saveWideText=True,
dataFileName=filename)

save a log file for detail verbose info

logFile = logging.LogFile(filename+‘.log’, level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file

endExpNow = False # flag for ‘escape’ or other condition => quit the exp
frameTolerance = 0.001 # how close to onset before ‘same’ frame

Start Code - component code to be run after the window creation

— Setup the Window —

win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType=‘pyglet’, allowStencil=False,
monitor=‘testMonitor’, color=[-1,-1,-1], colorSpace=‘rgb’,
backgroundImage=‘’, backgroundFit=‘none’,
blendMode=‘avg’, useFBO=True,
units=‘height’)
win.mouseVisible = False

Add a welcome message

welcome_message = visual.TextStim(
win=win, text=“Welcome and thank you for participating in this experiment.\n\n”
“During this experiment, you will be watching an episode of 'I’m a celebrity…get me out of here!, which will include eight commercial breaks. \n\nIf at any point you feel uncomfortable, you have the option to leave the experiment. Simply raise your hand, and the experiment will be stopped for you.”,
pos=(0, 0), color=‘white’, height=0.04)

Add an instructions message

instructions_message = visual.TextStim(
win=win, text=“The experiment is about to begin, please sit back, relax, and enjoy the show :)\n\n”
“Please find a comfortable seating position, relax, and enjoy the TV show. It’s important to minimize movement as much as possible, as any movement could potentially introduce significant noise into the data.\n\n”
“Please note that there will be a 90-second time interval before the experiment starts. This period is designed to record your baseline data.”,

pos=(0, 0), color='white', height=0.04)

Add a fixation cross

fixation_cross = visual.TextStim(
win=win, text=“+”,
pos=(0, 0), color=‘white’, height=0.05)

store frame rate of monitor if we can measure it

expInfo[‘frameRate’] = win.getActualFrameRate()
if expInfo[‘frameRate’] != None:
frameDur = 1.0 / round(expInfo[‘frameRate’])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess

— Setup input devices —

ioConfig = {}

Setup iohub keyboard

ioConfig[‘Keyboard’] = dict(use_keymap=‘psychopy’)

ioSession = ‘1’
if ‘session’ in expInfo:
ioSession = str(expInfo[‘session’])
ioServer = io.launchHubServer(window=win, **ioConfig)
eyetracker = None

create a default keyboard (e.g. to check for escape)

defaultKeyboard = keyboard.Keyboard(backend=‘iohub’)

— Initialize components for Routine “trial” —

movie = visual.MovieStim(
win, name=‘movie’,
filename=‘C:/Users/yx21446/OneDrive - University of Bristol/Desktop/PhD stimuli/1A.mp4’, movieLib=‘ffpyplayer’,
loop=False, volume=1.0, noAudio=False,
pos=(0, 0), size=(2.5, 2.5), units=win.units,
ori=0.0, anchor=‘center’,opacity=None, contrast=1.0,
depth=0
)

Create some handy timers

globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.Clock() # to track time remaining of each (possibly non-slip) routine

— Prepare to start Routine “trial” —

continueRoutine = True

Show the welcome message for 10 seconds or until a key is pressed

welcome_message.setAutoDraw(True)
timer = core.CountdownTimer(10.0) # 10 seconds countdown
while continueRoutine and timer.getTime() > 0:
win.flip()
if event.getKeys(): # Check for any key press to skip the message
break
welcome_message.setAutoDraw(False) # Hide the welcome message

Show the instructions message for 10 seconds or until a key is pressed

instructions_message.setAutoDraw(True)
timer = core.CountdownTimer(10.0) # 10 seconds countdown
while continueRoutine and timer.getTime() > 0:
win.flip()
if event.getKeys(): # Check for any key press to skip the message
break
instructions_message.setAutoDraw(False) # Hide the instructions message

Show the fixation cross for 10 seconds

fixation_cross.setAutoDraw(True)
timer = core.CountdownTimer(10.0) # 10 seconds countdown
while continueRoutine and timer.getTime() > 0:
win.flip()

fixation_cross.setAutoDraw(False) # Hide the fixation cross before starting the video

instructions_message.setAutoDraw(False) # Hide the instructions message before starting the video

update component parameters for each repeat

keep track of which components have finished

trialComponents = [movie]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, ‘status’):
thisComponent.status = NOT_STARTED

reset timers

t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock=“now”)
frameN = -1

— Run Routine “trial” —

routineForceEnded = not continueRoutine
while continueRoutine and routineTimer.getTime() < 60.0:
# get current time
t = routineTimer.getTime()
tThisFlip = win.getFutureFlipTime(clock=routineTimer)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame

# *movie* updates

# if movie is starting this frame...
if movie.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
    # keep track of start time/frame for later
    movie.frameNStart = frameN  # exact frame index
    movie.tStart = t  # local t and not account for scr refresh
    movie.tStartRefresh = tThisFlipGlobal  # on global time
    win.timeOnFlip(movie, 'tStartRefresh')  # time at next scr refresh
    # add timestamp to datafile
    thisExp.timestampOnFlip(win, 'movie.started')
    # update status
    movie.status = STARTED
    movie.setAutoDraw(True)
    movie.play()

# if movie is stopping this frame...
if movie.status == STARTED:
    # is it time to stop? (based on global clock, using actual start)
    if tThisFlipGlobal > movie.tStartRefresh + 60-frameTolerance:
        # keep track of stop time/frame for later
        movie.tStop = t  # not accounting for scr refresh
        movie.frameNStop = frameN  # exact frame index
        # add timestamp to datafile
        thisExp.timestampOnFlip(win, 'movie.stopped')
        # update status
        movie.status = FINISHED
        movie.setAutoDraw(False)
        movie.stop()

# check for quit (typically the Esc key)
if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
    core.quit()
    if eyetracker:
        eyetracker.setConnectionState(False)

# check if all components have finished
if not continueRoutine:  # a component has requested a forced-end of Routine
    routineForceEnded = True
    break
continueRoutine = False  # will revert to True if at least one component still running
for thisComponent in trialComponents:
    if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
        continueRoutine = True
        break  # at least one component has not yet finished

# refresh the screen
if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
    win.flip()

— Ending Routine “trial” —

for thisComponent in trialComponents:
if hasattr(thisComponent, “setAutoDraw”):
thisComponent.setAutoDraw(False)
movie.stop()

using non-slip timing so subtract the expected duration of this Routine (unless ended on request)

if routineForceEnded:
routineTimer.reset()
else:
routineTimer.addTime(-60.000000)

— End experiment —

Flip one final time so any remaining win.callOnFlip()

and win.timeOnFlip() tasks get executed before quitting

win.flip()

these shouldn’t be strictly necessary (should auto-save)

thisExp.saveAsWideText(filename+‘.csv’, delim=‘auto’)
thisExp.saveAsPickle(filename)
logging.flush()

Hello,
It’s pretty much impossible for me to help and debug your code. If you could be a bit more specific about the problem, what you have been trying to do, and what exactly you are trying to achieve, then maybe I could help you.
But seeing a wall of code will take enormous effort to help you, and no one will probably be able to help you that way.

Thanks,
Chen

Hey Chen, first of all thanks a lot for your help :slight_smile: What I am trying to do is quite easy to explain but as easy to implement - at least for me. Basically, I am going to show participant a documentary. Within this documentary, there will be 8 ad breaks (randomized) every 4 minutes that represents my stimuli. The documentary lasts for approximately 45 minutes, while the 8 breaks for approximately 2. Basically, I need the documentary to automatically pause when the ad stimuli starts, and the automatically play again when the ad stimuli ends. Thank you :slight_smile:

Hey Edoardo,
I created an example for you showing what you were describing. I didn’t test it online, but if you need it to work online, it should be easy to prepare from the example I created.

In the example, there are 2 main elements, the documentary component (doc) and the ad components (ad1, ad2, and ad3).

We don’t set the documentary’s length; we will trigger the end of the routine through code.
In the example, the length of the documentary is 60 seconds long.
We set the start and duration of each advertisement. For example, the length of each ad is 5 seconds long.

Now to the code.
At the beginning of the experiment, we create a list of all our ads videos (paths). We then shuffle them:

#Begin Routine
ads = ['vids/Ad1.mp4', 'vids/Ad2.mp4', 'vids/Ad3.mp4']
shuffle(ads)

If we go back to the advertisement component, we can notice that we set each advertisement to be an element from the ads list (ads[0]):
image
This way, we get a random ad each time.

Now some more code to the movie pausing and playing.
We run the following code for each frame:

# Each Frame
time_intervals = [(5, 10), (15, 20), (25, 30)]
adNumber = 0

if adNumber < len(time_intervals):
    t_min, t_max = time_intervals[adNumber]
    
    if t_min <= t <= t_max:
        doc.pause()
    else:
        doc.play()
        adNumber += 1

First, we set the time intervals of the ads. So the first ad will start at 5 and finish playing at 10. Make sure it matches the ad components.
Then we create a counter (adNumber) to follow which number of ad is being played.

For each time interval (in other words, for each ad), we run a code that pauses the documentary at t_min, and plays it again at t_max.

Lastly, another piece of code we need is code to finish the routine:
(Sum of the documentary + ads length)

#Each Routine

if t >= 75:
    continueRoutine = False

Here is a download for the experiment:
Ads.zip (1.2 MB)

Let me know if you have any questions and if it helped you.

Thanks,
Chen

OMG Chen you’re simply AMAZING!!! Thanks a lot! I will make sure to upload the experiment once is completed :smiley: The next step would be sending triggers to an EEG (Brainproduct) and to a GSR machine (Biopac). Any ideas on how to do it? Is there a tutorial/paper somewhere?
Thanks again Chen, have a wonderful weekend!

Hello,
Glad I could help :slight_smile:
I don’t have experience with the products you mentioned, but a quick search will get you to here:
Brainproduct:
https://psychopy.org/api/hardware/brainproducts.html

BIOPAC:

Looks like a good start.
Chen

Thanks a lot Chen! Sorry for the late reply but I have been very busy with the experiment, and I am still having problems :frowning:
There are two main issues:

  1. I changed yours stimuli with mine (12 in total), and the first iteration works just fine: the doc stops when the stimulus plays and then starts again when the stimulus finishes. Problem is that this is true only for the first iteration, for the second and the third stimulus the doc does not stop and keeps on playing on the background. Also, I would like to have a pause of second between ad an documentary.
  2. The format of the stimuli is not the same as the one of the doc as I am using videos from TikTok, Facebook, Youtube etc… the problem is that when the stimulus plays, even in iteration 1 when the doc plays, the doc is still in the background although not playing. I need the doc to completely disappears when the stimuli play.
  3. I tried to put in a welcome, instructions, and fixation cross but when I do so the counting gets all messy. For example the doc does not count every 5 but every 10 withouth me touching the code. I’d like to insert a goodbye message at the end as well. (UPDATE: I think I successfully managed this part by creating 2 separate routines, one for the welcome and instructions and one for the fixation cross, and then the goodbye message).
    Can you please help me?

P.S. Can you please tell me what the yellow line simbolyzes?

Thanks a lot Chen, you are amazing!