如何使用python-vlc精确记录30秒的流?

问题描述 投票:0回答:1

我正在尝试通过python-vlc记录RTP流正好30秒,但输出文件有时小于或大于我想要的视频长度。

注意:我尝试使用ffmpeg,但无法正确解码流,因此决定使用python-vlc。

这是我的代码:

import vlc
import time

vlcInstance = vlc.Instance("--demux=ts")
player1 = vlcInstance.media_player_new()
media1 = vlcInstance.media_new("rtp://239.194.115.71:5000")
media1.add_option("sout=file/ts:sample.mpg")
limiter = 0

player1.set_media(media1)

player1.play()
time.sleep(1)

while player1.is_playing():
    if limiter > 30:
        player1.stop()
        media1.release()
        break
    limiter = limiter + 1
    time.sleep(1)

我可以使用什么方法来始终将流记录恰好30秒?

python python-3.x vlc libvlc python-vlc
1个回答
0
投票

我使用opencv-python获取输出文件的当前帧数和fps,并使用它来计算视频长度。

import vlc
import time
import cv2
import os.path

vid_len = 0
vlcInstance = vlc.Instance("--demux=ts")
player1 = vlcInstance.media_player_new()
media1 = vlcInstance.media_new("rtp://239.194.115.71:5000")
media1.add_option("sout=file/ts:sample.mpg")
player1.set_media(media1)

player1.play()

#checks if the length of the output exceeds 30 seconds
while vid_len < 30:
    time.sleep(1)
    #checks if the file exists and not empty
    if os.path.isfile('sample.mpg') and (os.path.getsize('sample.mpg') > 0):
        video_file = cv2.VideoCapture('sample.mpg')
        frames = int(video_file.get(cv2.CAP_PROP_FRAME_COUNT))
        fps = (video_file.get(cv2.CAP_PROP_FPS))
        vid_len = frames/fps

player1.stop()
media1.release()

“

© www.soinside.com 2019 - 2024. All rights reserved.