首页 > 解决方案 > Python 播放 ffpyplayer 后删除文件

问题描述

在我的项目中,我喜欢用 cv2 播放视频,用 ffpyplayer 播放声音。

除了最后一行之外,代码如下所示:

os.remove("testinn.mp4")

给出一个错误:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'testinn.mp4'. 

我可以得出结论,该文件尚未正确关闭,因此无法删除。问题不在于 cv2(如果 ffpyplayer 部分被删除,它确实会删除)。但是在ffpyplayer。

您如何关闭此文件以便在播放后将其删除?

import os
    
import cv2
import numpy as np
from ffpyplayer.player import MediaPlayer

video_name = "testinn.mp4"
window_name = "window"
interframe_wait_ms = 30

cap = cv2.VideoCapture(video_name)
player = MediaPlayer(video_name)
if not cap.isOpened():
    print("Error: Could not open video.")
    exit()

cv2.namedWindow(window_name, cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
audio_frame, val = player.get_frame()
while (True):
    ret, frame = cap.read()
    if not ret:
        print("Reached end of video, exiting.")
        break

    cv2.imshow(window_name, frame)
    if cv2.waitKey(interframe_wait_ms) & 0x7F == ord('~'):
        print("Exit requested.")
        break

cap.release()
cv2.destroyAllWindows()
os.remove("testinn.mp4")

标签: pythonpython-3.xcv2

解决方案


你忘了关MediaPlayer

根据文件

close_player(self)
关闭播放器和所有资源。

我曾经pathlib.Path.unlink()删除文件,但应该与os.remove. 签出pathlib.Path,因为这提供了方便且强大的高级界面。

>>> from ffpyplayer.player import MediaPlayer
>>> from pathlib import Path
>>> vid = Path("x:/cyan uwu.mp4")
>>> player = MediaPlayer(vid.as_posix())

# Can't delete while MediaPlayer is open

>>> vid.unlink()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "...\Python39\lib\pathlib.py", line 1343, in unlink
    self._accessor.unlink(self)
PermissionError: [WinError 32] "<error message in your language>" : 'x:\\cyan uwu.mp4'

# After closing you're free to remove

>>> player.close_player()
>>> vid.unlink()
>>> 

推荐阅读