python - 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")
解决方案
你忘了关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()
>>>
推荐阅读
- scala - Spark:如何过滤列并执行操作并最终将所有列写入文件?
- scala - 如何在 Map 中按键添加值
- java - ANDROID:删除重复字符串
- node.js - TypeError:无法读取未定义的属性“localeCompare”
- c# - 如何使用 C# 在 WPF 中为视频添加注释/书签
- c# - 合并两个 Observable 时保留排序
- python - 使用 Google Cloud Speech 转录音频文件时如何解决“请求包含无效参数错误”
- python - 谷歌应用引擎在使用 python 下载时重命名我的文件
- swift - 根据部分限制单元格选择
- dgraph - 使用空白节点的 DGraph 最简单突变