1

How can i give random name to a output file in ffmpeg.

I want to give the filename as current date_time (ex.2020-3-18-10-13-4.mkv).

I don't want to give a fix name such as output.mkv.

import os
import subprocess
import tkinter as tk
import datetime

root = tk.Tk()

os.chdir(f'C://Users/{os.getlogin()}/desktop/')
def recording_voice():
  global p
  p =subprocess.Popen('ffmpeg -i video.avi -i audio.wav -c:v copy -c:a aac -strict experimental -strftime 1 "%Y-%m-%d_%H-%M-%S.mkv"' ,stdin=subprocess.PIPE)


rec_btn = tk.Button(text='Start merging', width=20, command=recording_voice)
rec_btn.pack()


root.mainloop()
amit9867
  • 229
  • 4
  • 16
  • Why `random` is it just temporary - if so you might want to look into the `tempfile` module. – AChampion Mar 18 '20 at 04:54
  • @AChampion no its not temporary. and i want to set current date time as the file name. each time the program run it will allocate the current date time to the filename. – amit9867 Mar 18 '20 at 05:00

1 Answers1

2

You may use now.strftime and string concatenation:

Assuming you don't actually want random file name, but just want name that includes current date and time, you may use the following code:

import subprocess
from datetime import datetime

# datetime object containing current date and time
now = datetime.now()

# Build file name with current date and time (with inverted commas):
dt_file_name = now.strftime('"ex.%Y-%m-%d_%H-%M-%S.mkv"')

# Concatenate file name to ffmpeg command line (use plus for strings concatenation):
p = subprocess.Popen('ffmpeg -i video.avi -i audio.wav -c:v copy -c:a aac -strict experimental -strftime 1 ' + dt_file_name, stdin=subprocess.PIPE)

You may also use now.strftime in one line (shorter but less elegant):

p = subprocess.Popen(now.strftime('ffmpeg -i video.avi -i audio.wav -c:v copy -c:a aac -strict experimental -strftime 1 "ex.%Y-%m-%d_%H-%M-%S.mkv"'), stdin=subprocess.PIPE)

In case you want to make sure you are getting different file name, you may also include the microseconds:

dt_file_name = now.strftime('"ex.%Y-%m-%d_%H-%M-%S-%f.mkv"')
Rotem
  • 30,366
  • 4
  • 32
  • 65
  • is there any way to hide the cmd window. as i don;t want to show the cmd window and want to run this process in background only. – amit9867 Mar 19 '20 at 09:12
  • Yes, check the following [post](https://superuser.com/questions/326629/how-can-i-make-ffmpeg-be-quieter-less-verbose) – Rotem Mar 19 '20 at 09:39
  • no it doesn't help its for error and i want to hide the cmd window while i run this code. – amit9867 Mar 19 '20 at 09:48
  • 1
    I can't see any command window, but you may check [here](https://stackoverflow.com/questions/7006238/how-do-i-hide-the-console-when-i-use-os-system-or-subprocess-call) – Rotem Mar 19 '20 at 10:03