python代码实现视频播放(可用键盘控制实现不同视频跳转)

我这个代码实现的需求是这样的:

现在我有多个视频文件,其中一个视频是作为默认的不断循环的视频,也就是我在运行这个代码后就会默认一直播放这段视频。当我有跳转需求,我就会通过键盘的数字键实现跳转,跳转视频播放完之后,又会回到默认视频。

这个需求感觉挺小众的,不过实现起来也不是很难,可能有演出或者播放需求的朋友会用到?

1. 配置环境和库

这里建议用anaconda创建虚拟环境

conda create -n videoplay python=3.8

然后切换到虚拟环境

conda activate videoplay

下载库

pip install opencv-python

配置环境流程:

安装anaconda

创建虚拟环境videoplay,conda create -n videoplay python=3.8

切换到虚拟环境videoplay, conda activate videoplay

安装第三方库opencv,pip install opencv-python

将videoplay文件夹拷贝至C盘根目录下

将视频文件拷贝至c:\videoplay\video_folder文件夹内

需要循环播放的背景视频命名为0.mp4,其他视频按照序列1、2、3等重命名(视频格式采用mp4)

使用流程:

在菜单内找到"Anaconda Prompt (Anaconda3)"并运行

将弹出的cmd窗口移动至副屏

cmd窗口输入cd c:\videoplay并回车

继续输入conda activate videoplay并回车

执行python videoplay.py并回车,将会在主屏幕弹出视频窗口

在cmd窗口内,输入数字编号将会切换至指定的视频文件

在视频窗口内,输入数字编号将会切换至指定的视频文件

2. 运行代码

python 复制代码
import os
import subprocess
import threading
import time

# 视频文件夹路径
video_folder = r"./video_folder"

# 当前播放的视频编号
current_video = 0
next_video = 0

# 退出标志
exit_flag = False

# 存储视频文件列表
video_files = []

def load_videos():
    """从指定文件夹中加载所有视频"""
    global video_files
    video_files = [f for f in os.listdir(video_folder) if f.endswith('.mp4')]
    video_files.sort()  # 排序文件
    for idx, file in enumerate(video_files):
        print(f"{idx}号视频:{file}")

def play_video(video_index):
    """使用 Windows Media Player 播放视频"""
    global exit_flag
    video_path = os.path.abspath(os.path.join(video_folder, video_files[video_index]))

    # 使用 Windows Media Player 播放视频并全屏
    subprocess.Popen([r"C:\Program Files (x86)\Windows Media Player\wmplayer.exe", video_path, "/fullscreen"], shell=True)

    while not exit_flag:
        time.sleep(1)

def input_listener():
    """监听输入,改变播放的视频"""
    global next_video, exit_flag
    while not exit_flag:
        try:
            user_input = input(f"请输入0-{len(video_files)-1}切换视频 (输入'q'退出): ")
            if user_input == 'q':
                exit_flag = True
                break
            user_input = int(user_input)
            if user_input in range(len(video_files)):
                next_video = user_input
        except ValueError:
            print(f"无效输入,请输入0-{len(video_files)-1}之间的数字")

if __name__ == "__main__":
    load_videos()  # 动态加载视频

    # 启动视频播放线程
    video_thread = threading.Thread(target=play_video, args=(current_video,))
    video_thread.start()

    # 启动输入监听线程
    input_thread = threading.Thread(target=input_listener)
    input_thread.start()

    while not exit_flag:
        if next_video != current_video:
            current_video = next_video
            # 终止当前播放的 Windows Media Player 进程
            subprocess.call(['taskkill', '/F', '/IM', 'wmplayer.exe'])
            # 播放新选择的视频
            video_thread = threading.Thread(target=play_video, args=(current_video,))
            video_thread.start()

    video_thread.join()
    input_thread.join()
相关推荐
m0_7482323917 分钟前
基于OpenCV和Python的人脸识别系统_django
python·opencv·django
dme.42 分钟前
Python爬虫selenium验证-中文识别点选+图片验证码案例
爬虫·python
东方-教育技术博主1 小时前
wps中zotero插件消失,解决每次都需要重新开问题
python
镰圈量化1 小时前
当电脑上有几个python版本Vscode选择特定版本python
开发语言·vscode·python
宇努力学习1 小时前
如何本地部署seepseek
python·ai·ollama·deepseek
橙狮科技2 小时前
使用 GPTQ 进行 4 位 LLM 量化
人工智能·python·语言模型
开开心心就好2 小时前
娱乐使用,可以生成转账、图片、聊天等对话内容
windows·python·智能手机·软件工程·娱乐·软件需求
愚昧之山绝望之谷开悟之坡2 小时前
ragflow-RAPTOR到底是什么?请通俗的解释!
python
背太阳的牧羊人2 小时前
RAG检索中使用一个 长上下文重排序器(Long Context Reorder) 对检索到的文档进行进一步的处理和排序,优化输出顺序
开发语言·人工智能·python·langchain·rag
007_rbq2 小时前
XUnity.AutoTranslator-Gemini——调用Google的Gemini API, 实现Unity游戏中日文文本的自动翻译
人工智能·python·游戏·机器学习·unity·github·机器翻译