I'm working on a cancel button that cancels the ffmpeg video & audio merging process when pressed. But while loop doesn't keep looping once ffmpeg starts execution, while loop continues to loop after ffmpeg finished the process. I couldn't really figure it out, sorry if it's duplicate.
I know the code looks really silly but I'm kinda doomed, any help will be greatly appreciated. Thanks in advance.
from tkinter import *
import ffmpeg
import threading
def start_ffmpeg_thread(audio_part, video_part, path):
threading.Thread(target=start_ffmpeg, args=(audio_part, video_part, path)).start()
def start_ffmpeg(audio_part, video_part, path):
while True:
if is_cancelled:
break
threading.Thread(target=ffmpeg_func, args=(audio_part, video_part, path)).start()
def ffmpeg_func(audio_part, video_part, path):
ffmpeg.output(audio_part, video_part, path).run(overwrite_output=True)
def cancel_ffmpeg():
global is_cancelled
is_cancelled = True
is_cancelled = False
root = Tk()
video_part = ffmpeg.input("<path_video_part>")
audio_part = ffmpeg.input("<path_audio_part>")
path = "<path>"
button_1 = Button(root, text="Start", command=lambda: start_ffmpeg_thread(audio_part, video_part, path))
button_1.pack(pady=30, padx=30)
button_2 = Button(root, text="Stop", command=cancel_ffmpeg)
button_2.pack(pady=30, padx=30)
root.mainloop()
For gracefully closing FFmpeg sub-process, we may write
'q'
tostdin
pipe of FFmpeg sub-process as described in my following answer.In order to have it possible to write
'q'
, we may execute FFmpeg sub-process as follows:ffmpeg_process
allows us to access the sub-process and terminate it.For keeping the code simple, we may declare
ffmpeg_process
asglobal
variable.Updated
ffmpeg_func
method:Updated
start_ffmpeg
method:The above code allows executing FFmpeg only if it's not running.
Updated
cancel_ffmpeg
method:Note:
Your implementation of
start_ffmpeg
executesthreading.Thread
in a loop, and that executes FFmpeg sub-process in a loop.We have to remove the
while True
from the above method.Updated code sample:
In case you are planning to allow multiple instances of FFmpeg sub-processes, you may insert the
ffmpeg_process
into a list, for keeping track over all the sub-processes.For closing all the sub-processes at once, just iterate the list.