def transcode(self, input_file): ff = ffmpy.FFmpeg( inputs={input_file: None}, outputs={dest: '-f mxf -c:v mpeg2video -c:a pcm_s24le -g 1 -pix_fmt yuv422p' ' -b:v 30M -r 25 -field_order tt -flags +ildct+ilme -dc 10 -top 1 -color_trc bt709 -y'} ) print "attempting transcode using ffmpeg command:", ff.cmd try: ff.run() print "transcode succesfull (I think), removing", input_file os.remove(input_file) except: print "transcode unsuccesfull"
def convert(path_dl, name): """ Convert videos and extract music then delete video file """ extension_in = '.3gp' extension_out = '.mp3' ffmpy_options = ffmpy.FFmpeg( inputs={path_dl + name + extension_in: None}, outputs={path_dl + name + extension_out: None}) print("Convertissement en musique en cours") ffmpy_options.run() print("Convertissement Terminé") os.remove(path_dl + name + extension_in)
def concat_audio(files, path): if os.path.exists(path): os.remove(path) with open('list.txt', 'w') as file: for f in files: file.write("file '" + f + ".WAV'\n") ffmpy.FFmpeg(inputs=None, outputs={ path: '-f concat -safe 0 -i list.txt -c copy -loglevel ' + loglevel }).run() os.remove('list.txt')
def compose_vid(folder, vid): print('composing video') j = 1 try: j = cpu_count() except: pass ff = ffmpy.FFmpeg( inputs={str(folder) + '/frame%05d.png': None}, outputs={str(vid): '-loglevel panic -y -threads ' + str(j)}) print(ff.cmd) ff.run() print('output video ' + str(vid) + ' written')
def convertAudio(self): myFile = os.fsdecode(self) if myFile.endswith(".wav"): ff = ffmpy.FFmpeg( inputs={myFile: None}, outputs={ myFile + '.jpg': ['-lavfi', 'showspectrumpic=s=1024x512:legend=disabled'] }) ff.run() else: raise Exception("File was not in .wav format") return
def concat(path): if path is not None: file = open('{}targetlist.txt'.format(path), w) #writes ordered list of transport streams to file audio, name = '', '' files = natsorted(os.listdir(path), key=lambda y: y.lower()) for stream in files: if stream.endswith('.ts'): file.write(each) else: audio = stream name = os.path.splitext(stream)[0] print 'Concatenating video...' ff = ffmpy.FFmpeg( executable='./ffmpeg/ffmpeg', inputs={'{}targetlist.txt'.format(path): '-f concat -safe 0'}, outputs={ '{}DEAF.mp4'.format(path): '-loglevel 100 -y -c copy -bsf:a aac_adtstoasc' }) ff.run() file_to_upload = '{}{}FANTASITCALLY_TRANSCODED.mp4'.format(path, name) fff = ffmpy.FFmpeg( executable='./ffmpeg/ffmpeg', inputs={ '{}DEAF.mp4'.format(path): [None], '{}{}'.format(path, audio): [None] }, outputs={ file_to_upload: '-loglevel 100 -c:v copy -c:a aac -strict experimental' }) file.close() return file_to_upload
def record_finished(): if 'video' not in request.files and 'carId' not in request.form: abort(400) source_file = request.files['video'] # create a blank mongo record and get the id for creating a unique local folder # the document will be used for saving the ipfs add result hash token = str(g.mongo_collection.insert_one({}).inserted_id) target_file = os.path.join('data/video', token, secure_filename(source_file.filename)) os.makedirs(os.path.dirname(target_file), exist_ok=True) source_file.save(target_file) # for ipfs video player support, must have file in directory named 'video.mp4' ff = ffmpy.FFmpeg( inputs={target_file: None}, outputs={os.path.join(os.path.dirname(target_file), 'video.mp4'): '-strict -2'} ) ff.run() # add to ipfs ipfs_folder_to_add = os.path.dirname(target_file) ipfs_add_res = g.ipfs_api_conn.add(ipfs_folder_to_add, recursive=True) # since adding the folder only works randomly, just save the video url folder_obj = None for item in ipfs_add_res: if item['Name'].endswith('video.mp4'): folder_obj = item # insert into ethereum chain as a contract transaction_id = g.eth_contract_factory.deploy(args=[folder_obj['Hash'], request.form['carId']]) g.mongo_collection.update_one( { '_id': ObjectId(token) }, { '$set': { 'carId': request.form['carId'], 'data': folder_obj, 'transactionId': transaction_id } } ) return 'you did it'
def ytdl(_input, _quality, _format, _convert): ydl_opts = { 'format': _quality, 'logger': MyLogger(), 'progress_hooks': [my_hook], 'outtmpl': '%(title)s.%(ext)s', } # put the video link on this list video_list = list() for i in _input: video_list.append("https://www.youtube.com/watch?v={}".format(i)) print(video_list) with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(video_list) if _convert: sourcedir = os.getcwd() if not os.path.exists("{}/videos".format(sourcedir)): os.makedirs("{}/videos".format(sourcedir)) filext = "" if _quality == 'worst': filext = "3gp" if _quality == 'best': filext = "mp4" for file in os.listdir(sourcedir): if file.endswith(".{}".format(filext)): filename = file.split('.') length = len(filename) ekst = filename[length - 1] newname = "" for i in range(0, length - 1): filename[i] = re.sub(r'[^\w\s]', '', filename[i]) filename[i] = re.sub(r"\s+", '-', filename[i]) newname += filename[i] os.rename("{}/{}".format(sourcedir, file), "{}/{}.{}".format(sourcedir, newname, ekst)) print("now converting . . .") inputFile = "{}/{}.{}".format(sourcedir, newname, ekst) outputFile = "{}/{}.{}".format(sourcedir, newname, _format) # subprocess.call(["ffmpeg", "-i", inputFile, outputFile]) ff = ffmpy.FFmpeg(inputs={inputFile: None}, outputs={outputFile: '-c:a copy'}) ff.run() # os.remove(inputFile) os.rename( outputFile, "{}/videos/{}.{}".format(sourcedir, newname, _format)) print("done")
def merge_medium(audio_fn, audio_dir='./data/audio', media_dir='./data/media', out_dir='./data/segmented', top_db=50, thres_duration=100): ''' Segment a YouTube Video to parts , where the endpoints (start/stop points) are determined by `segment_audio()` fubction. The segmented Videos are stored locally in the `out_dir` directory. Input: audio_fn: see `segment_audio()` media_path: path to where the media files (Video files) are located top_db: see `segment_audio()` thres_duration: see `segment_audio()` Output: None ''' # cutoff points of audio track cutoffs = segment_audio(audio_dir=audio_dir, audio_fn=audio_fn, top_db=top_db, thres_duration=thres_duration) # match medium (Video) to audio track media_filenames = os.listdir(media_dir) matched_medium = [ medium_fn for medium_fn in media_filenames if medium_fn.split('.') [0].split('_')[-1] == audio_fn.split('.')[0].split('_')[-1] ] matched_medium = matched_medium[0] # print(matched_medium) # paths & directories medium_path = os.path.join(media_dir, matched_medium) medium_ = matched_medium.split('.')[0] os.makedirs(out_dir, mode=0o777, exist_ok=True) # segment Video for idx in range(1, len(cutoffs)): start = time.strftime('%H:%M:%S', time.gmtime(cutoffs[idx - 1])) end = time.strftime('%H:%M:%S', time.gmtime(cutoffs[idx])) output_name = medium_ + '_' + str(idx) + '.mp4' output = os.path.join(out_dir, output_name) inp = {medium_path: ['-ss', start]} oup = {output: ['-to', end, '-c', 'copy']} ff = ffmpy.FFmpeg(inputs=inp, outputs=oup) # print(ff.cmd) ff.run()
def download_video(url: str, path: str): # append /.json to the url if not url.endswith('/'): url += '/' url += '.json' response = reqs.json_url(url=url) # This will fail if url is not from reddit or is not a video try: is_video = response[0]['data']['children'][0]['data']['is_video'] if not is_video: return 1 except: return 1 # parse audio/video info mpd_list_link = response[0]['data']['children'][0]['data']['media'][ 'reddit_video']['dash_url'] mpd_response = reqs.get(url=mpd_list_link) mpd_xml = mpd_response.text # get links for audio and video base_link = response[0]['data']['children'][0]['data']['url'] data = re.findall('<BaseURL>(.*?)</BaseURL>', mpd_xml) hq_video_link = base_link + '/' + data[0] audio_link = base_link + '/' + data[-1] temp_dir = tempfile.gettempdir() temp_video_dir = temp_dir + '/' + next(tempfile._get_candidate_names()) temp_audio_dir = temp_dir + '/' + next(tempfile._get_candidate_names()) # store data in temp files reqs.ulibreq.urlretrieve(hq_video_link, temp_video_dir) reqs.ulibreq.urlretrieve(audio_link, temp_audio_dir) ff = ffmpy.FFmpeg(inputs={ temp_video_dir: None, temp_audio_dir: None }, outputs={path: " -c copy"}) # failsafe try: ff.run() os.remove(temp_audio_dir) os.remove(temp_video_dir) except ffmpy.FFRuntimeError: return 1 return 0
def saveThumbnails(input, output, count): meta = getMdeiaInof(input) duration = float(meta['streams'][0]['duration']) frameRate = int(meta['streams'][0]['r_frame_rate'].split("/")[0])/int(meta['streams'][0]['r_frame_rate'].split("/")[1]) _,ts = getTimestamp(duration,frameRate) r = count/duration print(duration) print(frameRate) print(duration*frameRate) # ff = ffmpy.FFmpeg(inputs={input: None}, outputs={output + '_%10d.png': '-r 60 -ss 00:00:10 -t 00:00:01'}) ff = ffmpy.FFmpeg(inputs={input: None}, outputs={output + '_%4d.png': '-s:v 640*360 -r %f -ss 00:00:00 -t %s'%(r,ts)}) print(ff.cmd) ff.run()
def extract_frames(vid, folder): print('extracting frames') j = 1 try: j = cpu_count() except: pass ff = ffmpy.FFmpeg(inputs={str(vid): None}, outputs={ str(folder) + '/frame%05d.png': '-loglevel panic -y -threads ' + str(j) }) print(ff.cmd) ff.run()
def main(): try: ff = ffmpy.FFmpeg( inputs={sys.argv[1]: None}, outputs={ sys.argv[4]: '-ss {} -s 1280x720 -aspect 16:9 -map 0:0 -map 0:1 -c:v libx264 -b:v 1000k -c:a aac -b:a 128k -f mp4 -t {}' .format(sys.argv[2], sys.argv[3]) }) ff.cmd ff.run() except: print('usage: fichero in duracion error : ', sys.exc_info()[0]) sys.exit(1)
def embed_audio(audio_signal, ext='.mp3', display=True): """ Write a numpy array to a temporary mp3 file using ffmpy, then embeds the mp3 into the notebook. Args: audio_signal (AudioSignal): AudioSignal object containing the data. ext (str): What extension to use when embedding. '.mp3' is more lightweight leading to smaller notebook sizes. Defaults to '.mp3'. display (bool): Whether or not to display the object immediately, or to return the html object for display later by the end user. Defaults to True. Example: >>> import nussl >>> audio_file = nussl.efz_utils.download_audio_file('schoolboy_fascination_excerpt.wav') >>> audio_signal = nussl.AudioSignal(audio_file) >>> audio_signal.embed_audio() This will show a little audio player where you can play the audio inline in the notebook. """ ext = f'.{ext}' if not ext.startswith('.') else ext audio_signal = deepcopy(audio_signal) ffmpy, IPython = _check_imports() sr = audio_signal.sample_rate tmpfiles = [] with _close_temp_files(tmpfiles): tmp_wav = NamedTemporaryFile(mode='w+', suffix='.wav', delete=False) tmpfiles.append(tmp_wav) audio_signal.write_audio_to_file(tmp_wav.name) if ext != '.wav' and ffmpy: tmp_converted = NamedTemporaryFile(mode='w+', suffix=ext, delete=False) tmpfiles.append(tmp_wav) ff = ffmpy.FFmpeg( inputs={tmp_wav.name: None}, outputs={ tmp_converted.name: '-write_xing 0 -codec:a libmp3lame -b:a 128k -y' }) ff.run() else: tmp_converted = tmp_wav audio_element = IPython.display.Audio(data=tmp_converted.name, rate=sr) if display: IPython.display.display(audio_element) return audio_element
def geraThumbsPasta(self, dirOrigem, dirDestino): # files = [file for file in glob.glob(dirOrigem+"/**", recursive=True)] files = [file for file in glob.glob(dirOrigem + "/*")] posDP = dirOrigem.find(":") if posDP < 0: posDP = 0 #self.__writeLog("Convertendo "+str(len(files))+" arquivos") nfile = 1 for fileName in files: newName = fileName.replace(dirOrigem, dirDestino) os.makedirs(os.path.dirname(newName), exist_ok=True) newNameTmp = newName + "_thumbs.jpg" processed = False ext = os.path.splitext(filename)[1][1:].upper() try: if os.path.isfile( fileName) and ext in self.VIDEO_TYPES and os.stat( fileName).st_size > 100000: nFrames = self.getNumFrames(fileName) if nFrames > (self.THUMBS_X * self.THUMBS_Y): self.__writeLog("Convertendo de: " + fileName + " para " + newNameTmp) outputpars = '-loglevel panic -y -vf "select=not(mod(n\,' + str( nFrames // 25) outputpars += ')),scale=320:240,tile=' + str( self.THUMBS_X) + '+' + str( self.THUMBS_Y) + '" -frames 1' ff = ffmpy.FFmpeg(inputs={fileName: None}, outputs={newNameTmp: outputpars}) ff.run() processed = True self.PROCESSED_VIDEO_FILES.append( os.path.split(os.path.abspath(fileName))[1]) except: self.__writeLog("Erro no processamento de: " + str(sys.exc_info())) continue #self.__writeLog(str(nfile)+"/"+str(len(files))) if processed: size = os.stat(fileName).st_size newsize = os.stat(newNameTmp).st_size #self.__writeLog(fileName+": "+str(size)+ " -> "+str(newsize)+ " "+newNameTmp) elif os.path.isfile(fileName): copy2(fileName, newName) # os.replace(fileName,newName) print()
def run(self, m3u8_url, dir=''): self.dir = dir if self.dir and not os.path.isdir(self.dir): os.makedirs(self.dir) r = self.session.get(m3u8_url, timeout=10) if r.ok: body = r.content if body: ts_list = [urljoin(m3u8_url, n.strip()) for n in body.decode().split('\n') if n and not n.startswith("#")] if len(ts_list) == 1: file_name = ts_list[0].split('/')[-1].split('?')[0] chunk_list_url = "{0}/{1}".format(m3u8_url[:m3u8_url.rfind('/')], file_name) r = self.session.get(chunk_list_url, timeout=20) if r.ok: body = r.content ts_list = [urljoin(m3u8_url, n.strip()) for n in body.decode().split('\n') if n and not n.startswith("#")] # re-retrieve to get all ts file list ts_list = zip(ts_list, [n for n in range(len(ts_list))]) ts_list = list(ts_list) if ts_list: self.ts_total = len(ts_list) self.ts_current = 0 g1 = gevent.spawn(self._join_file) self._download(ts_list) g1.join() else: print("Failed status code: {}".format(r.status_code)) infile_name = os.path.join(self.dir, self._result_file_name.split('.')[0]+'_all.'+self.result_file_name.split('.')[-1]) outfile_name = infile_name.split('.')[0] + '.mp4' sys.stdout.write(' > Converting to mp4... ') sys.stdout.flush() try: ff = ffmpy.FFmpeg( global_options='-loglevel panic', inputs={infile_name: None}, outputs={outfile_name: ['-c','copy']} ) ff.run() # delete source file after done os.remove(infile_name) self._result_file_name = outfile_name print('Done!') except ffmpy.FFExecutableNotFoundError: print('Skipping! Because "ffmpeg" not installed.') self._result_file_name = infile_name except ffmpy.FFRuntimeError: print('Error! ffmpeg exited with non-zero status code.') self._result_file_name = infile_name
def convert(vid, source, stream, skip): print(vid + source) video = vid filename, ext = os.path.splitext(vid) filename = filename.replace("'", "") streams = [] for item in stream: if item['codec_type'] == 'video': my_video = item streams.append("-map 0:{}".format(item['index'])) elif item['codec_type'] == 'audio': mapper = "-map 0:{}".format(item['index']) streams.append(mapper) if 'srr' in ext: return elif skip and 'mp4' in ext: return elif 'mp4' in ext: rename_me = os.path.join(source, filename + '.m4v') path = os.path.join(source, vid) os.rename(path, rename_me) video = rename_me ext = 'mp4' else: ext = 'mp4' print('file: {} ext: {}'.format(filename, ext)) my_stream = " ".join(streams) if int(my_video['width']) > 720: opts = "-c:v libx265 -crf 20 -vf '{}:trunc(ow/a/2)*2' -metadata title='{}' -map_metadata 0 {}".format( scale, filename.replace("'", ""), my_stream) else: opts = "-c:v libx265 -crf 20 -metadata title='{}' -metadata:s:a:0 language=eng -map_metadata 0 {}".format( filename.replace("'", ""), my_stream) out_vid = '{}.{}'.format(filename, ext) if os.path.isfile(out_vid): print(os.getsize(out_vid)) if os.getsize(out_vid) > 10000000: print("File has already been converted") return else: os.remove(out_vid) ff = ffmpy.FFmpeg(inputs={video: None}, outputs={out_vid: opts}) print(ff.cmd) ff.run() return
def download(self, download_url, time): output_name = self.cid + '_' + str(time) + '.mp4' output = os.path.join(self.output_dir, output_name) ffmpeg_cmd = ffmpy.FFmpeg( r'C:\Program Files (x86)\ffmpeg-4.0.2\bin\ffmpeg.exe', '-t 0:01:15', inputs={download_url: None}, outputs={output: None}) print('Start downloading and merging with ffmpeg...') print(ffmpeg_cmd.cmd) ffmpeg_cmd.run()
def transcode(self, resourceid): resource_dir = os.path.join(self.download_dir, resourceid) if os.path.exists(resource_dir) and os.path.exists(os.path.join(resource_dir, 'metadata')): with open(os.path.join(resource_dir, 'metadata')) as f: metadata = json.load(f) if metadata['complete']: os.chdir(os.path.join(resource_dir)) ff = ffmpy.FFmpeg(inputs={'video.m3u8': ['-protocol_whitelist', 'file,http,https,tcp,tls,crypto']}, outputs={metadata['title'] + '.mp4':""}) #os.system('ffmpeg -protocol_whitelist "file,http,https,tcp,tls,crypto" -i video.m3u8 ccc.mp4') print(ff.cmd) ff.run() return
def create_movie(args, log, frame_files, i): movie_input, movie_output, file_location, frame_file_path = create_movie_name(args, log, frame_files, i) #create the movie ff = ffmpy.FFmpeg( inputs={None: ['-y', '-pattern_type', 'glob'], movie_input: None}, outputs={None: ['-force_key_frames', '0.0,0.04,0.08', '-vcodec', 'libx264', '-acodec', 'aac'], movie_output: None} ) ff.run() return file_location + movie_output
def downloadFile(self, file): filePath = file['file_path'] fileName, fileExtension = path.splitext(filePath) imgInd = self.getInd() imgInd += 1 urllib.request.urlretrieve(f"https://api.telegram.org/file/bot{botToken}/{filePath}", f"image{imgInd}{fileExtension}") print (f"saved image{imgInd}{fileExtension}") if (fileExtension == ".mp4"): print (f"Converting video to gif: image{imgInd}.gif") ff = ffmpy.FFmpeg(inputs={f'image{imgInd}{fileExtension}': None}, outputs={f'image{imgInd}.gif': '-vf scale=w=240:h=240:force_original_aspect_ratio=decrease'} ) ff.run() os.remove(f'image{imgInd}{fileExtension}') self.writeInd(imgInd) self.loadImage(imgInd)
def solve(self, task): filename = task.value r = requests.get(self.base_url + filename) if not r.ok: Logger.error('Can\'t download file "%s"' % filename) return None mp4_tf = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) mp4_tf.write(r.content) mp4_tf.close() Logger.info('Saved audio to %s' % mp4_tf.name) Logger.info('Converting it into WAV') wav_tf = tempfile.NamedTemporaryFile(suffix='.wav', delete=False) wav_tf.close() ff = ffmpy.FFmpeg(inputs={mp4_tf.name: None}, outputs={wav_tf.name: ['-y']}) ff.run() with sr.AudioFile(wav_tf.name) as audio_file: audio = self.sr.record(audio_file) Logger.info('Uploading file to Google Speech Recognition') try: # for testing purposes, we're just using the default API key # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` # instead of `r.recognize_google(audio)` recognized = self.sr.recognize_google(audio) Logger.info('Google Speech Recognition thinks you said "%s"' % recognized) except sr.UnknownValueError: Logger.error( 'Google Speech Recognition could not understand audio') return None except sr.RequestError as e: Logger.error( 'Could not request results from Google Speech Recognition service; %s' % e) return None quote = self._find_suitable_quote(recognized) if quote is None: return None author = quote[':a'].split() name = author[0] return name
def _get_video_duration_with_ffmpeg(self, file_path): """Get video duration using ffmpeg binary. Based on function ffmpeg_parse_infos inside repo https://github.com/Zulko/moviepy/moviepy/video/io/ffmpeg_reader.py The MIT License (MIT) Copyright (c) 2015 Zulko Returns a video duration in second :param file_path: video file path :type file_path: string :raises IOError: :return: duration of video clip in seconds :rtype: float """ FFMPEG_BINARY = os.getenv("FFMPEG_BINARY") # Open the file in a pipe, read output ff = ffmpy.FFmpeg( executable=FFMPEG_BINARY, inputs={file_path: ""}, outputs={None: "-f null -"}, ) _, error = ff.run( stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) infos = error.decode("utf8", errors="ignore") lines = infos.splitlines() if "No such file or directory" in lines[-1]: raise IOError(("Error: the file %s could not be found!\n" "Please check that you entered the correct " "path.") % file_path) # get duration (in seconds) by parsing ffmpeg file info returned by # ffmpeg binary video_duration = None decode_file = False try: if decode_file: line = [line for line in lines if "time=" in line][-1] else: line = [line for line in lines if "Duration:" in line][-1] match = re.findall("([0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9])", line)[0] video_duration = helper._convert_to_seconds(match) except Exception: raise IOError( f"error: failed to read the duration of file {file_path}.\n" f"Here are the file infos returned by ffmpeg:\n\n{infos}") return video_duration
def upload(): if request.method == 'POST': if 'file' not in request.files: flash('No file') return redirect(url_for('index')) file = request.files['file'] if file.filename == '': flash('No file selected') return redirect(url_for('index')) if file: # Save the file filename = secure_filename(file.filename) name = secrets.token_hex(6) title, ext = os.path.splitext(filename) file_path = os.path.join(app.config['UPLOAD_FOLDER'], name + ext) file.save(file_path) if ext[1:].lower() not in ['mp4']: if ext[1:].lower() == 'mov': # Convert mov to mp4 ff = ffmpy.FFmpeg( inputs={file_path: None}, outputs={ os.path.join(app.config['UPLOAD_FOLDER'], name + '.' + 'mp4'): None }) ff.run() ext = '.mp4' else: flash('Incompatible file type') return redirect(url_for('upload')) # Insert data into the database db = get_db() db.execute( 'INSERT INTO video (id, ext, title) VALUES (?, ?, ?)', (name, ext[1:], title)) db.commit() flash('Uploaded video') return redirect(url_for('view', id=name)) return render_template('upload.html')
def convert_single_video_v2_125_60(name): f = FULL_VIDEO_PATH + name out_video = OUTPUT_FULL_VIDEO_PATH_125_60 + name if os.path.isfile(out_video): print('Video already created. Skip it!') return ff = ffmpy.FFmpeg( inputs={f: '-r 24'}, outputs={ out_video: '-r 4 -filter:v scale=126:126,select="not(mod(n-1\,6))" -sws_flags spline -vsync 0 -pix_fmt yuv420p -vcodec libx264 -level 41 -refs 4 -preset veryslow -trellis 2 -me_range 24 -x264opts crf=16:ratetol=100.0:psy=0 -threads 6 -an -f mp4 -y' }) # print(ff.cmd) ff.run(stdout=open('nul', 'w'), stderr=open('nul', 'w'))
def stream1(camera, fileout, instance): global ffProcesses ffProcesses.append( ffmpy.FFmpeg( inputs={camera: '-y -hide_banner -loglevel panic'}, outputs={ fileout: '-c:v copy -c:a copy -f segment -strftime 1 -segment_time ' + str(config.segmentLength) + ' -segment_format mp4' })) try: ffProcesses[instance].run() except ffmpy.FFRuntimeError, e: if e.exit_code and e.exit_code != 255: raise
def convert_files(self, mp3_files): """ :param mp3_files: :return: """ for mp3_file in mp3_files: dst_mp3 = self.create_dst_location(mp3_file) ff = ffmpy.FFmpeg( inputs={mp3_file: None}, outputs={dst_mp3: '-acodec libmp3lame -b:a 256k'}) try: ff.run() except ffmpy.FFRuntimeError: print('File {} already exists.'.format(dst_mp3))
def extract_audio(video_file_name, output_format='wav'): #video_file_name = video_file_name.replace(' ', '\ ') file_name_without_format = "".join(video_file_name.split('.')[:-1]) output_file_name = file_name_without_format + '.' + output_format if(os.path.isfile(output_file_name)): os.remove(output_file_name) inputs = {video_file_name : None} outputs = {output_file_name : None} ff = ffmpy.FFmpeg(inputs=inputs, outputs=outputs) #print ff.cmd ff.run() return output_file_name
def convertVideo(video_id): """ Converts a video from webm to mp4 """ path = get_attributes(video_id, ["File Path"])[0] newPath = "out/toCheck/"+video_id+".mp4" ff = ffmpy.FFmpeg( inputs={path: "-y"}, outputs={newPath: "-strict -2"} ) ff.run() delFile(path) information_csv[information_csv["UUID"] == video_id]["Format"] = ".mp4" information_csv[information_csv["UUID"] == video_id]["File Path"] = newPath
def split_video(input_path, output_path, from_time, duration): """ Split the video Arguments: input_path - path of input video output_path - path to store output video from_time - in minutes:seconds, example 01:10 for one minute ten seconds duration - in seconds, for example 10 """ #'-ss 00:00:15.00 -t 00:00:10.00 -c:v copy -c:a copy' parameters = '-ss 00:{}.00 -t 00:00:{}.00 -c:v copy -c:a copy'.format(from_time, duration) ff = ffmpy.FFmpeg( inputs={input_path: None}, outputs={output_path: parameters}) ff.run() print('Splitted video starting from {}, duration: {} seconds'.format(from_time, duration))