Save Stimulus as a Video File (e.g., .mp4)

from psychopy import visual, core, event
import time

# create window
# later adjust size to tablet!!!
win0 = visual.Window([800, 600], screen = 0, monitor = 'testMonitor',
                     fullscr=False, color=[0, 0, 0], units='pix')

gratingStimulus = visual.GratingStim(win=win0, tex='sin', units='pix', pos=(
    0.0, 0.0), size=800, sf=0.01, ori=0.0, phase=(0.0, 0.0))

win0.getMovieFrame(buffer='back')
startTime = time.time()
runTime = 15 # run stimulus for 15 seconds

while(time.time() - startTime < 15):
    win0.getMovieFrame(buffer='back') # get every upcoming frame?
    gratingStimulus.setPhase(0.02, '+')
    # 1st parameter is for speed of drifting
    # 2nd parameter is for direction of drifint ('+': left to right)
    gratingStimulus.draw()
    win0.flip()

    if len(event.getKeys()) > 0:
        break
    event.clearEvents()
print("Play time: ", time.time()-startTime)    
win0.close()
win0.saveMovieFrames(fileName='testMovie.mp4') # save frames as video file

I am new to coding, so please dumb it down if possible!
My goal is to simply save this drifting grating stimulus as a video file, preferably in .mp4 format.
I have attached screenshots of the Python console and the video file.
When I run the code, the drifting grating plays for 15 seconds, but the recording part does not work.
No error message in the console.
But the video file only shows grey screen for 10 seconds, not even 15 seconds which I had set the while loop to last in my code.

Thank you in advance.

Hi There,

Try moving the location of where the window frame is saved to just after the win.flip. The code below should do the trick.

Becca


from psychopy import visual, core, event
import time

# create window
# later adjust size to tablet!!!
win0 = visual.Window([800, 600], screen = 0, monitor = 'testMonitor',
                     fullscr=False, color=[0, 0, 0], units='pix')

gratingStimulus = visual.GratingStim(win=win0, tex='sin', units='pix', pos=(
    0.0, 0.0), size=800, sf=0.01, ori=0.0, phase=(0.0, 0.0))

win0.getMovieFrame(buffer='back')
startTime = time.time()
runTime = 15 # run stimulus for 15 seconds

while(time.time() - startTime < 15):
 #   win0.getMovieFrame(buffer='back') # get every upcoming frame?
    gratingStimulus.setPhase(0.02, '+')
    # 1st parameter is for speed of drifting
    # 2nd parameter is for direction of drifint ('+': left to right)
    gratingStimulus.draw()
    win0.flip()
    win0.getMovieFrame()

    if len(event.getKeys()) > 0:
        break
    event.clearEvents()
print("Play time: ", time.time()-startTime)    
win0.close()
win0.saveMovieFrames(fileName='testMovie.mp4') # save frames as video file
1 Like

Thank you, it’s working now!

fantastic - please can you mark the answer as a ‘solution’ so that future users can see this is resolved.

Becca