1.概述
在一个测试项目中,有一个需求是要在测试过程中,播放一段living video streaming. 上网查了一下,可以利用ffmpeg,opencv等技术来实现。但是实验后发现效果不太理想,而测试用例里建议是使用vlc来播放这个视频流,故采用python-vlc模块,来实现。经测试,效果满足测试需求。
2.opencv demo
虽然没有采用opencv的方案,但是发现这个 demo在对http视频流方面还是可以使用的。
import numpy as np
import cv2
#cap = cv2.VideoCapture(0)
cap = cv2.VideoCapture(r'http://admin:admin@192.168.2.161:8081')
# 定义解码器并创建VideoWrite对象
# linux: XVID、X264; windows:DIVX
# 20.0指定一分钟的帧数
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while (cap.isOpened()):
ret, frame = cap.read()
if ret == True:
frame = cv2.flip(frame, 0)
# 写入帧
out.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# 释放内存
cap.release()
out.release()
cv2.destroyAllWindows()
3.python-vlc demo
这个demo就是项目中所用到的用于播放rtsp视频流的模块,主要难点可能会出现在环境搭建上。
import os
import vlc
import time
def get_player(url='rtsp://192.168.2.134:8554/live'):
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new(url)
Media.get_mrl()
player.set_media(Media)
player.play()
return player
def get_player_state(player):
is_playing = player.is_playing()#playing:1 ;other:0
will_play = player.will_play()
get_state = player.get_state()
print 'is_playing: ',is_playing
print 'will_play: ', will_play
print 'get_state: ', get_state
def get_player_para(player):
length = player.get_length()
width = player.video_get_width()
size = player.video_get_size()
title = player.video_get_title_description()
video_track = player.video_get_track_description()
audio_track = player.audio_get_track_description()
fps = player.get_fps()
rate = player.get_rate()
track_count = player.video_get_track_count()
track = player.video_get_track()
print 'length: ',length
print 'width: ',width
print 'size: ', size
print 'title: ',title
print 'video_track: ',video_track
print 'audio_track: ',audio_track
print 'fps: ',fps
print 'rate: ', rate
print 'track_count: ',track_count
print 'track: ',track
def vlc_main():
timestamp = time.time()
while time.time()-timestamp < 400:
player = get_player()
time.sleep(1) # must delay at least one second
if player.is_playing():
time.sleep(10)
get_player_para(player)
player.video_take_snapshot(num=0, psz_filepath=os.getcwd(), i_width=1080, i_height=360)
#time.sleep(10)
player.release()
return
player.release()
player.release()
print '###########################'
print 'Fail: cannot find any video'
print '###########################'
if __name__ == '__main__':
vlc_main()