The problem is that I can not exit the while loop without stopping the entire program.
When I execute the code on my Raspberry Pi, the camera starts recording, but when I want to end the video and press Ctrl+c, the entire program stops instead of continuing after the while loop. I thought the signal handler would catch the keyboard interrupt but it does not.
My code:
import picamera
import signal
from time import sleep
from subprocess import call
def signal_handler(signal, frame):
global interrupted
interrupted = True
signal.signal(signal.SIGINT, signal_handler)
interrupted = False
# Setup the camera
with picamera.PiCamera() as camera:
camera.resolution = (1640, 922)
camera.framerate = 30
# Start recording
camera.start_recording("pythonVideo.h264")
while True:
sleep(0.5)
print("still recording")
if interrupted:
print("Ctrl+C pressed")
camera.stop_recording()
break
# Stop recording
#camera.stop_recording()
# The camera is now closed.
print("We are going to convert the video.")
# Define the command we want to execute.
command = "MP4Box -add pythonVideo.h264 convertedVideo.mp4 -fps 30"
#Execute command.
call([command], shell=True)
# Video converted.
print("Video converted.")
What I tried:
bflag = True
while bflag ==True:
sleep(0.5)
print("still recording")
if interrupted:
print("Ctrl+C pressed")
camera.stop_recording()
bflag = False
Error:
pi@raspberrypi:~/Documents/useThisFolder $ python cookieVideo.py
still recording
still recording
still recording
still recording
still recording
^Cstill recording
Ctrl+C pressed
Traceback (most recent call last):
File "cookieVideo.py", line 29, in <module>
camera.stop_recording()
File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 1193, in stop_recording
'port %d' % splitter_port)
picamera.exc.PiCameraNotRecording: There is no recording in progress on port 1
This would do it:
while True:
try:
sleep(0.5)
print("still recording")
except KeyboardInterrupt:
print("Ctrl+C pressed")
camera.stop_recording()
break