Camera capture code not recording any video

Hi,
I’m working on an experiment in v3.2.4 and trying to add a camera to record the participants face while they are looking at a fixation cross, and then when they are viewing a stimulus. I’ve added the camera as a code component in Builder. I’ve successfully got it to save a video file for each presentation, but only the first video file generated actually has any content, and the rest are only a few hundred bytes and give me a 0xc10100be can’t play error when I open them. I haven’t been able to figure out why the recording only works for the first instance - here’s the code I’m using for the camera:

(begin experiment)

capture = cv2.VideoCapture(0)

(begin routine)
```fourcc = cv2.VideoWriter_fourcc(*'mp4v')
videoWriter = cv2.VideoWriter('C:\\Users\\hc122\\Desktop\\InteroStudy2020\\video captures\\IAPS_%s_%s_%s_%s.mp4' %(expInfo['Participant'],stimIAPS,condition,trialsPract.thisTrialN), fourcc, 30.0,(640,480))

(each frame)
```ret, frame = capture.read()
if ret:
    videoWriter.write(frame)

(end routine)
```capture.release()
videoWriter.release()
cv2.destroyAllWindows()

At a guess the problem is something to do with how the component ends as the camera is still lit up indicating it's in use after the stimulus ends and the participant has to fill out some responses, and I don't know if that's what is causing it to not record again?

Any help would be appreciated, thanks in advance!