Webcam recording doesn't close on each loop?

Hi! I’m trying to create an experiment where, on each iteration of a loop, the webcam will turn on at the beginning of one routine and off at the end of that routine. The desired result is 1 separate video file recorded from each iteration of the loop.

OS MacOS Catalina 10.15.7 (unfortunately can’t update due to other software we need)
PsychoPy version 2023.2.3
Standard Standalone? yes.

For testing purposes I’ve created a minimal experiment with one routine in a loop x 3 reps.
In this code component there is:

Begin Experiment

from psychopy.hardware import camera
webcam = camera.Camera(device='Brio 101', name='webcam')

Begin Routine

if webcam.isNotStarted:
    webcam.open()

if not webcam.isRecording:
    webcam.record()

End Routine

if webcam.isRecording:
    webcam.stop()
    videopath = '/webcam_'+data.utils.getDateStr()+'.mp4'
    webcam.save(videopath)
    #webcam.close()

I have tried this two ways: with and without calling .close() on each loop.

If I DO NOT include webcam.close(), the result is 3 videos (1 per rep) but there is no stoppage of recording. That is, what I want is 3 videos of 5 seconds each, but what I get is 3 videos of 5s, 10s, and 15s lengths respectively (i.e. the later iterations include the recorded data from previous iterations as well). With this toy example it might work to just crop the videos later, but my real task is actually much longer and the file sizes will be too big.

If I DO include webcam.close(), the experiment crashes on the second loop with pid:3747, printing “RuntimeError: Cannot close MediaPlayer, already closed.”

Additionally, I have tried with the Builder “Camera” component instead of custom code, and using opencv for the backend in place of the default ffmpeg, to no avail.

Any advice?

Returning to this, I wasn’t able to get .close() to work correctly, but I did find a useable workaround:

I removed webcam.close(), as this continually returned the “already closed” error on the second loop each time.

Instead, I moved the line creating the camera component (webcam =
camera.Camera(device=‘Brio 101’, name=‘webcam’) from “Begin Experiment” to “Begin Routine”. This essentially creates the camera component anew each loop, overwriting the old one so that the video data from the previous iteration is no longer stored in it, and I can record and save a video file of the present loop only.