Python exercises to auto-play jpg and mp4

The Python code listed below auto-play jpg and mp4 in "files" sub-folder, run on Windows 11. 



Remark: These Python programs require OpenCV and ffpyplayer. Since I encountered some issues installing OpenCV on the latest Python 3.14, I created a Python 3.12 virtual environment to install OpenCV and ffpyplayer.

Related: Create Python virtual environment in Windows 11

play_jpg.py
"""
Python to auto play all jpg in "files" sub-folder.

To install cv2:
> pip install opencv-python
"""
import cv2
import os
import time
import platform

sys_info_text = "Python " + platform.python_version() + "\n" +\
                "Running on " + platform.platform() + "\n" +\
                cv2.__name__ + " " + cv2.__version__
print("==================================================")
print("""Python to auto play all jpg in "files" sub-folder.""")
print()
print(sys_info_text)
print("==================================================")

def show_images(folder="files", delay=6, max_size=800):
    # sort .jpg and add to list
    images = [os.path.join(folder, f) for f in os.listdir(folder) if f.lower().endswith(".jpg")]
    images.sort()

    if not images:
        print("⚠️ No JPG found")
        return

    # display window
    cv2.namedWindow("Slideshow", cv2.WINDOW_AUTOSIZE)

    while True:
        for img_path in images:
            print(f"🖼 Display: {img_path}")
            img = cv2.imread(img_path)
            if img is None:
                print(f"⚠️ Can't read {img_path}")
                continue

            h, w = img.shape[:2]
            # limit the width and height <= max_size
            scale = min(max_size / w, max_size / h, 1.0)
            new_w, new_h = int(w * scale), int(h * scale)

            # resize
            if scale < 1.0:
                img = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)

            cv2.imshow("Slideshow", img)

            # Press 'q' to Quit
            start = time.time()
            while time.time() - start < delay:
                if cv2.waitKey(100) & 0xFF == ord('q'):
                    cv2.destroyAllWindows()
                    return

        #time.sleep(1)

# Start
show_images("files", delay=4, max_size=800)



play_mp4.py
"""
Python to auto play all mp4 in "files" sub-folder.

To install cv2:
> pip install opencv-python

To install ffpyplayer:
> pip install ffpyplayer
"""

import cv2
import os
from ffpyplayer.player import MediaPlayer
import ffpyplayer
import time
import platform

sys_info_text = "Python " + platform.python_version() + "\n" +\
                "Running on " + platform.platform() + "\n" +\
                cv2.__name__ + " " + cv2.__version__ + "\n" +\
                ffpyplayer.__name__ + " " + ffpyplayer.__version__
print("==================================================")
print("""Python to auto play all mp4 in "files" sub-folder.""")
print()
print(sys_info_text)
print("==================================================")

def play_video(video_path):
    cap = cv2.VideoCapture(video_path)
    player = MediaPlayer(video_path)

    while True:
        ret, frame = cap.read()
        if not ret:
            break

        # play audio
        audio_frame, val = player.get_frame()
        if val != 'eof' and audio_frame is not None:
            img, t = audio_frame

        # play video
        cv2.imshow("Video", frame)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cap.release()
            cv2.destroyAllWindows()
            return False  # press 'q' to quit
    cap.release()
    cv2.destroyAllWindows()
    return True

def loop_videos(folder="files"):
    # sort all mp4
    videos = [os.path.join(folder, f) for f in os.listdir(folder) if f.lower().endswith(".mp4")]
    videos.sort()

    if not videos:
        print("⚠️ No MP4 found!")
        return

    while True:  # Infinite loop
        for video in videos:
            print(f"▶ Playing: {video}")
            ok = play_video(video)
            if not ok:
                print("⏹ Quit!")
                return
        # pause a while after all played
        time.sleep(1)

# Start
loop_videos("files")



Comments

Popular posts from this blog

Drive 320x240 ILI9341 SPI TFT using ESP32-S3 (NodeMCU ESP-S3-12K-Kit) using TFT_eSPI library, in Arduino Framework.

480x320 TFT/ILI9488 SPI wih EP32C3 (arduino-esp32) using Arduino_GFX Library