| 1 |
import av |
| 2 |
|
| 3 |
av.logging.set_level(av.logging.VERBOSE) |
| 4 |
|
| 5 |
|
| 6 |
""" |
| 7 |
This is written for MacOS. Other platforms will need to init `input_` differently. |
| 8 |
You may need to change the file "0". Use this API to list all devices: |
| 9 |
|
| 10 |
av.enumerate_input_devices("avfoundation") |
| 11 |
|
| 12 |
""" |
| 13 |
|
| 14 |
input_ = av.open( |
| 15 |
"0", |
| 16 |
format="avfoundation", |
| 17 |
container_options={"framerate": "30", "video_size": "1920x1080"}, |
| 18 |
) |
| 19 |
output = av.open("out.mkv", "w") |
| 20 |
|
| 21 |
# Prefer x264, but use Apple hardware if not available. |
| 22 |
try: |
| 23 |
encoder = av.Codec("libx264", "w").name |
| 24 |
except av.FFmpegError: |
| 25 |
encoder = "h264_videotoolbox" |
| 26 |
|
| 27 |
output_stream = output.add_stream(encoder, rate=30) |
| 28 |
output_stream.width = input_.streams.video[0].width |
| 29 |
output_stream.height = input_.streams.video[0].height |
| 30 |
output_stream.pix_fmt = "yuv420p" |
| 31 |
|
| 32 |
try: |
| 33 |
while True: |
| 34 |
try: |
| 35 |
for frame in input_.decode(video=0): |
| 36 |
packet = output_stream.encode(frame) |
| 37 |
output.mux(packet) |
| 38 |
except av.BlockingIOError: |
| 39 |
pass |
| 40 |
except KeyboardInterrupt: |
| 41 |
print("Recording stopped by user") |
| 42 |
|
| 43 |
packet = output_stream.encode(None) |
| 44 |
output.mux(packet) |
| 45 |
|
| 46 |
input_.close() |
| 47 |
output.close() |