python使用opencv、vlc对直播连接进行视频播放

42 篇文章 0 订阅
1 篇文章 0 订阅

安装opencv:

pip install opencv-contrib-python==4.3.0.36

pip install python-vlc==3.0.10114

注:下载慢的话,加上清华源的链接。

 

直接使用python的vlc的工具进行播放:

import sys
import http.client
import time
from vlc import VideoMarqueeOption, Position, EventType, Instance


class RTSP_Client():
    pass


class VLC_Player():
    def __init__(self, url):
        self.url = url

    def start_with_marquee(self, timeout=60):
        """这种方案是可以带字幕的,根据vlc自带测试源码改写
     """

        movie = self.url
        # Need --sub-source=marq in order to use marquee below
        print(sys.argv[:])
        instance = Instance(["--sub-source=marq"] + sys.argv[1:])
        try:
            media = instance.media_new(movie)
        except (AttributeError, NameError) as e:
            sys.exit(1)
        player = instance.media_player_new()
        player.set_media(media)
        player.play()

        # Some marquee examples.  Marquee requires '--sub-source marq' in the
        # Instance() call above, see <http://www.videolan.org/doc/play-howto/en/ch04.html>
        player.video_set_marquee_int(VideoMarqueeOption.Enable, 1)
        player.video_set_marquee_int(VideoMarqueeOption.Size, 24)  # pixels
        player.video_set_marquee_int(VideoMarqueeOption.Position, Position.Bottom)
        player.video_set_marquee_int(VideoMarqueeOption.Timeout, 0)  # millisec, 0==forever
        player.video_set_marquee_int(VideoMarqueeOption.Refresh, 1000)  # millisec (or sec?)
        t = '%Y-%m-%d  %H:%M:%S'
        player.video_set_marquee_string(VideoMarqueeOption.Text, str_to_bytes(t))

        # Some event manager examples.  Note, the callback can be any Python
        # callable and does not need to be decorated.  Optionally, specify
        # any number of positional and/or keyword arguments to be passed
        # to the callback (in addition to the first one, an Event instance).
        event_manager = player.event_manager()
        event_manager.event_attach(EventType.MediaPlayerEndReached, end_callback)
        event_manager.event_attach(EventType.MediaPlayerPositionChanged, pos_callback, player)
        time.sleep(timeout)

    def start(self, timeout=60):
        """这种是最简方案,用来测试播放足够了
     """

        instance = Instance()
        player = instance.media_player_new()
        Media = instance.media_new(self.url)
        Media.get_mrl()
        player.set_media(Media)
        player.play()
        # 如果是看直播这里直接写while True 即可
        time.sleep(timeout)


def str_to_bytes(s):
    """Translate string or bytes to bytes.
    """
    if isinstance(s, str):
        return bytes(s, encoding="UTF-8")
    else:
        return s


def end_callback(event):
    print('End of media stream (event %s)' % event.type)
    sys.exit(0)


echo_position = False


def pos_callback(event, player):
    if echo_position:
        sys.stdout.write('\r%s to %.2f%% (%.2f%%)' % (event.type,
                                                      event.u.new_position * 100,
                                                      player.get_position() * 100))
        sys.stdout.flush()


if __name__ == "__main__":
    # 测试url为浙江卫视直播流
    # 注意换一下该url的地址为自己的想用的直播地址,可以现在VLC客户端播放器里试一下能否播放再运行该代码
    url = "http://14.29.60.40/live/5/30/847a4e1e97584d39a961f5604e90c1c4.m3u8?type=web.cloudplay"
    # url = "https://tv.cctv.com/live/cctv13/"
    p = VLC_Player(url)
    p.start(6000)

使用opencv进行直播视频播放:

import vlc
import ctypes
import time
import sys
import cv2
import numpy
from PIL import Image

vlcInstance = vlc.Instance()
# 机场内
# m = vlcInstance.media_new("")
# 机场外
# 记得换url,最好也和上面一样进行测试一下
url = ""
m = vlcInstance.media_new(url)
mp = vlc.libvlc_media_player_new_from_media(m)

# ***如果显示不完整,调整以下宽度和高度的值来适应不同分辨率的图像***
video_width = 1080
video_height = 640

size = video_width * video_height * 4
buf = (ctypes.c_ubyte * size)()
buf_p = ctypes.cast(buf, ctypes.c_void_p)

VideoLockCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p))


@VideoLockCb
def _lockcb(opaque, planes):
    # print("lock", file=sys.stderr)
    planes[0] = buf_p


@vlc.CallbackDecorators.VideoDisplayCb
def _display(opaque, picture):
    img = Image.frombuffer("RGBA", (video_width, video_height), buf, "raw", "BGRA", 0, 1)
    opencv_image = cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
    cv2.imshow('image', opencv_image)
    cv2.waitKey(10)


vlc.libvlc_video_set_callbacks(mp, _lockcb, None, _display, None)
mp.video_set_format("BGRA", video_width, video_height, video_width * 4)
while True:
    mp.play()
    time.sleep(1)

 

 

 
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值