webcam
webcam copied to clipboard
output to mp4
do we have an example to encode the file to a mp4 container? For example using ffmpeg.
func recordWebCam(savepath string) (err error) {
const (
recordSeconds = 20
intervalMs = 40 // approx 25 FPS (1000 / 25 = 40)
)
cam, err := webcam.Open("/dev/video0")
if err != nil {
return err
}
defer cam.Close()
if err = cam.StartStreaming(); err != nil {
return err
}
// convert:
// ffmpeg -f mjpeg -i output.webcam -c:v libx264 output.mp4
outFile, err := os.Create(filepath.Join(savepath, "output.webcam"))
if err != nil {
return err
}
defer outFile.Close()
ticker := time.NewTicker(time.Millisecond * intervalMs)
defer ticker.Stop()
timeout := uint32(intervalMs)
done := time.After(time.Second * time.Duration(recordSeconds))
for {
select {
case <-done:
return nil
case <-ticker.C:
err = cam.WaitForFrame(timeout)
switch err.(type) {
case nil:
case *webcam.Timeout:
continue
default:
return err
}
frame, err := cam.ReadFrame()
if err != nil {
return err
}
if len(frame) != 0 {
_, err := outFile.Write(frame)
if err != nil {
continue // skip bad write but keep recording
}
}
}
}
}
This is what i came up with