|
#使用vlc播放视频
import os
import random
import threading
import vlc
import time
class VideoPlayer:
def __init__(self):
self.instance = vlc.Instance()
self.player = self.instance.media_player_new()
def play_video(self, video_path):
"""使用 VLC 播放视频和音频"""
if not os.path.exists(video_path):
print(f"文件不存在: {video_path}")
return
# 停止任何当前正在播放的媒体
if self.player.is_playing():
self.player.stop()
# 加载并播放新的视频文件
media = self.instance.media_new(video_path)
self.player.set_media(media)
self.player.play()
# 等待视频加载并播放
time.sleep(1)
# 等待播放结束
while self.player.is_playing():
time.sleep(0.1)
def stop(self):
"""停止播放"""
if self.player.is_playing():
self.player.stop()
def play_media_from_folder(folder, player, stop_event):
"""随机播放文件夹内的 MP4 文件"""
files = [f for f in os.listdir(folder) if f.endswith('.mp4')]
while not stop_event.is_set():
if files:
selected_file = random.choice(files)
player.play_video(os.path.join(folder, selected_file))
def play_specific_media(folder, player, index):
"""播放指定序号的 MP4 文件"""
files = [f for f in os.listdir(folder) if f.endswith('.mp4')]
if 0 <= index < len(files):
player.play_video(os.path.join(folder, files[index]))
else:
print("序号超出范围。")
def list_media_files(folder):
"""列出文件夹内的 MP4 文件"""
files = [f for f in os.listdir(folder) if f.endswith('.mp4')]
for i, file in enumerate(files):
print(f"{i}: {file}")
return files
def main(folder1, folder2):
stop_event = threading.Event() # 控制播放线程的停止
player = VideoPlayer() # 创建一个播放器实例
# 启动随机播放线程
thread = threading.Thread(target=play_media_from_folder, args=(folder1, player, stop_event), daemon=True)
thread.start()
print("文件夹2内的 MP4 文件:")
list_media_files(folder2)
print("输入文件夹2内文件的序号播放对应媒体,输入 'exit' 退出:")
while True:
command = input()
if command.lower() == 'exit':
stop_event.set() # 设置停止事件,结束播放线程
player.stop() # 停止播放器
break
try:
index = int(command)
stop_event.set() # 暂停随机播放
thread.join() # 等待随机播放线程结束
play_specific_media(folder2, player, index)
stop_event.clear() # 清除停止事件,恢复随机播放
thread = threading.Thread(target=play_media_from_folder, args=(folder1, player, stop_event), daemon=True)
thread.start() # 重新启动随机播放线程
except ValueError:
print("无效的输入,请输入正确的序号。")
except IndexError:
print("无效的序号,请再试一次。")
if __name__ == '__main__':
folder1 = 'm1' # 替换为文件夹1的路径
folder2 = 'm2' # 替换为文件夹2的路径
main(folder1, folder2)
|
|