gpt4 book ai didi

python - 在 Tkinter 帧上播放带音频的视频

转载 作者:行者123 更新时间:2023-12-02 16:29:19 27 4
gpt4 key购买 nike

所以我正在尝试做一些非常笨拙的事情。我正在使用 opencv 和 ffpyplayer 尝试在 Tk 窗口上制作嵌入式视频播放器。

它确实有效,但我在同步音频和视频时遇到问题,我可以接近一个不错的结果,但过了一会儿它又不同步了。

整个代码:

import time, traceback, os, telepot
from tkinter import *
import cv2, youtube_dl # pip install opencv-python; pip install --upgrade
youtube_dl
from PIL import Image, ImageTk #
from io import BytesIO # io
from ffpyplayer.player import MediaPlayer # pip install ffpyplayer
from pytube import YouTube

_name_ = os.path.basename(os.path.realpath(__file__))
_path_ = os.path.realpath(__file__).replace(_name_, '')

class Screen(Frame):
'''
Screen widget: Embedded video player from local or youtube
'''
def __init__(self, parent, *args, **kwargs):
Frame.__init__(self, parent, bg = 'black')
self.settings = { # Inizialazing dictionary settings
"width" : 1024,
"height" : 576
}
self.settings.update(kwargs) # Changing the default settings
# Open the video source |temporary
self.video_source = _path_+'asd.mp4'

# Inizializing video and audio variables
self.vid = None
self.aux = None
# Canvas of the player
self.canvas = Canvas(self, width = self.settings['width'], height = self.settings['height'], bg = "black", highlightthickness = 0)
self.canvas.pack()

# NEED TO SYNC AUDIO
self.delay = 15 # Delay between frames of player

def update(self):
'''
Function: Start the player and keeps drawing the canvas
'''
if not self.vid or not self.aux: # If Audio or Video is missing stop everything
self.stop()
return None

# Get the frames and if video and audio are running
ret, frame = self.get_frame()
audio_frame, val = self.aux.get_frame()

# Drawing frames on canvas
if self.fb == 1: # Check if it's the first cycle, trying to make the audio start with the video
self.photo = ImageTk.PhotoImage(image = Image.fromarray(frame).resize((self.settings['width'], self.settings['height'])))
self.canvas.create_image(0,0, image = self.photo, anchor = 'nw')
self.fb = 0
self.aux.set_pause(False) # Starting the audio
elif ret and val != 'eof':
self.photo = ImageTk.PhotoImage(image = Image.fromarray(frame).resize((self.settings['width'], self.settings['height'])))
self.canvas.create_image(0,0, image = self.photo, anchor = 'nw')

self.after(self.delay, self.update) # Update for single frame, need to sync

def get_frame(self):
'''
Function: Draws the frames
'''
if self.vid.isOpened():
ret, frame = self.vid.read()
if ret:
# Return a boolean success flag and the current frame converted to BGR
return (ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
else:
return (ret, None)

def youTube(self, ID):
'''
Function: Gets the youtube video and starts it
'''
print("(TO REPLACE) : Downloading")
yt = YouTube("https://www.youtube.com/watch?v=" + ID)
stream = yt.streams.filter(progressive=True).first() # SEE THE POSSIBLE THINGS TO DOWNLOAD
stream.download(_path_, 'test')
print("(TO REPLACE) : Finished")
self.start(_path_+'\\test.mp4')

def start(self, _source):
'''
Function: Starts the player when gets input from keyboard(temporal) or Telegram
'''
try: # Stopping player if is already playing for a new video
self.stop()
except:
None

ff_opts = {'paused' : True} # Audio options
self.fb = 1 # Setting first cycle

if _source == 'local': # Checking which source use
self.vid = cv2.VideoCapture(self.video_source)
self.aux = MediaPlayer(self.video_source, ff_opts=ff_opts)
else:
self.vid = cv2.VideoCapture(_source)
self.aux = MediaPlayer(_source, ff_opts=ff_opts)

if not self.vid.isOpened():
raise ValueError("Unable to open video source")

self.update() # Starting the player

def stop(self):
'''
Function: Release and stop Video and Audio
'''
try: # Stopping video
self.vid.release()
self.vid = None
except:
pass
try: # Stopping audio
self.aux.toggle_pause()
self.aux = None
except:
pass
self.canvas.delete('all') # Resetting canvas

def __del__(self):
'''
Function: Release the video source when the object is destroyed
'''
if self.vid.isOpened():
self.vid.release()

class Mirror:
'''
Mainframe: Display where to put the widgets
'''
def __init__(self):
self.tk = Tk() # Creating the window
self.tk.configure(background = 'black')
self.tk.update()

# Setting up the FRAMES for widgets
self.bottomFrame = Frame(self.tk, background = 'black')
self.bottomFrame.pack(side = BOTTOM, fill = BOTH, expand = YES)

# Bindings and fullscreen setting
self.fullscreen = False
self.tk.bind("<Return>", self.toggle_fullscreen)
self.tk.bind("<Escape>", self.end_fullscreen)

# Screen, BOT
print("Inizializing Screen...")
self.screen = Screen(self.bottomFrame)
self.screen.pack(side = TOP)

self.tk.bind("<Key>", self.key) # Get inputs from keyboard

def key(self, event):
pressed = repr(event.char).replace("'", '')
if pressed == 's':
self.screen.stop()
elif pressed == 'a':
self.screen.start('local')
else:
print('fail')

def toggle_fullscreen(self, event = None):
self.fullscreen = True
self.tk.attributes("-fullscreen", self.fullscreen)

def end_fullscreen(self, event = None):
self.fullscreen = False
self.tk.attributes("-fullscreen", self.fullscreen)

def on_chat_message(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
message = str(msg.get('text'))

if 'https://youtu.be/' in message:
URL_VIDEO = message.split('https://youtu.be/')[1]
Mir.screen.youTube(URL_VIDEO)
elif 'stop' == message.lower():
Mir.screen.stop()

if __name__ == '__main__':
Mir = Mirror()
#bot = telepot.Bot(TELEGRAM_TOKEN)
#bot.message_loop(on_chat_message)
Mir.tk.mainloop()
#while 1:
#time.sleep(10)

特别是渲染帧的方法:
# NEED TO SYNC AUDIO
self.delay = 15 # Delay between frames of player

def update(self):
'''
Function: Start the player and keeps drawing the canvas
'''
if not self.vid or not self.aux: # If Audio or Video is missing stop everything
self.stop()
return None

# Get the frames and if video and audio are running
ret, frame = self.get_frame()
audio_frame, val = self.aux.get_frame()

# Drawing frames on canvas
if self.fb == 1: # Check if it's the first cycle, trying to make the audio start with the video
self.photo = ImageTk.PhotoImage(image = Image.fromarray(frame).resize((self.settings['width'], self.settings['height'])))
self.canvas.create_image(0,0, image = self.photo, anchor = 'nw')
self.fb = 0
self.aux.set_pause(False) # Starting the audio
elif ret and val != 'eof':
self.photo = ImageTk.PhotoImage(image = Image.fromarray(frame).resize((self.settings['width'], self.settings['height'])))
self.canvas.create_image(0,0, image = self.photo, anchor = 'nw')

self.after(self.delay, self.update) # Update for single frame, need to sync

我尝试了其他方法来使这件事起作用,并查看是否可以找到解决方案但没有成功,如果有人有一些想法或更好的解决方案来做到这一点,我将不胜感激。

我也尝试从 youtube 获取视频作为流而不需要先下载整个视频来播放它,我可以让视频工作,但我找不到让音频播放的方法,如果有人知道的话这样做我也想知道。

编辑:
所以视频的帧速率应该是 24、30 或 60,我应该检查视频的帧速率然后相应地设置延迟,我这样做的方式是我根据视频手动更改延迟帧速率试图通过反复试验使其同步。老实说,我对音频知之甚少,所以我对那些东西不屑一顾。

此外,要使整个代码运行,它需要来自电报机器人的 token 或本地视频文件才能播放。

最佳答案

好吧,我找到了一个更好的解决方案。我尝试再次使用 vlc 模块,之前我在使用它时遇到了问题,但在我通过它之后,我实际上找到了一种将 vlc 的输出打印到 的方法带 Canvas 的框架 .

它实际上很简单,我摆脱了 cv2 和 ffpyplayer 并使用了一个简单的 VLC 播放器

请注意,在我的情况下,Screen 是一个框架,所以要完成这项工作,只需使用“框架” .winfo_id() 要获取输出视频的 tk 帧的 id,音频也可以。然后只需使用播放器 .set_hwnd(ID) 将其设置为 vlc 播放器。

class Screen(Frame):
'''
Screen widget: Embedded video player from local or youtube
'''
def __init__(self, parent, *args, **kwargs):
Frame.__init__(self, parent, bg = 'black')
self.settings = { # Inizialazing dictionary settings
"width" : 1024,
"height" : 576
}
self.settings.update(kwargs) # Changing the default settings
# Open the video source |temporary
self.video_source = _path_+'asd.mp4'

# Canvas where to draw video output
self.canvas = Canvas(self, width = self.settings['width'], height = self.settings['height'], bg = "black", highlightthickness = 0)
self.canvas.pack()

# Creating VLC player
self.instance = vlc.Instance()
self.player = self.instance.media_player_new()


def GetHandle(self):
# Getting frame ID
return self.winfo_id()

def play(self, _source):
# Function to start player from given source
Media = self.instance.media_new(_source)
Media.get_mrl()
self.player.set_media(Media)

#self.player.play()
self.player.set_hwnd(self.GetHandle())
self.player.play()

关于python - 在 Tkinter 帧上播放带音频的视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55197752/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com