def convert_file_format(in_path, out_path): # Converts .swf filw to .mp4 file and saves new file at out_path from ffmpy import FFmpeg ff = FFmpeg(inputs={in_path: None}, outputs={out_path: None}) ff.run()
import sys import os from natsort import natsorted from ffmpy import FFmpeg path = sys.argv[1] if path == '.': path = os.getcwd() filenames = natsorted(os.listdir(path)) for filename in filenames: file = os.path.join(path, filename) if os.path.splitext(file)[1] == '.flv': tsfile = file[:file.rindex('.')] + '.ts' mp4file = tsfile[:tsfile.rindex('.')] + '.mp4' FFmpeg(inputs={ file: None }, outputs={ tsfile: '-y -c copy -bsf:v h264_mp4toannexb -f mpegts' }).run() os.remove(file) FFmpeg(inputs={ tsfile: None }, outputs={ mp4file: '-y -c copy -absf aac_adtstoasc' }).run() os.remove(tsfile)
def SeperateAVsteam(inpath, outpath): ff = FFmpeg( inputs={inpath: None}, outputs={outpath: '-f s16be -vn -ac 1 -ar 48000 -acodec pcm_s16be -y'}) print(ff.cmd) ff.run()
def convert_to_mp3(file_name_with_extension, file_name): input = f'tmp/{file_name_with_extension}' output = f'tmp/{file_name}.mp3' ff = FFmpeg(inputs={input: None}, outputs={output: None}) ff.run()
def run_conversion(): #creation of parser parser = argparse.ArgumentParser() parser.add_argument("-V", "--version", help="show program version", action="store_true") parser.add_argument("-I", "--input", help="input file") parser.add_argument("-N", "--number", help="number of seconds between thumbnails") # read arguments from the command line args = parser.parse_args() if args.version: print( "\nThis is a thumbnail generator for videos, still in development.\n" ) sys.exit() if args.input: video_input = args.input video_name = args.input.split('.')[0] else: print( "\nError: File not found or input not specified correctly. Be sure to include the -I flag for input." ) sys.exit() if args.number: num = args.number try: fps = str(1 / int(num)) except: print('\nError: Please enter a valid number for -N\n') sys.exit() else: num = 4 fps = str(.25) print('\nExecuting process on', args.input, '\n') #erase folders if filepath exists if os.path.exists(video_name + '_frames'): print('\nOverwriting existing directory...\n') shutil.rmtree(video_name + '_frames') os.makedirs(video_name + '_frames') #use FFmpeg to create thumbnails from video file. ff = FFmpeg(inputs={video_input: None}, outputs={ video_name + "_frames/thumb_%d" + ".png": ['-vf', 'fps=' + fps] }) # print(ff.cmd) # Print result try: print("\nGenerating Thumbnails...\n") ff.run() except: print('\nError: Error while running thumbnail conversion.\n') sys.exit() print("\nThumbnails generated successfully.\n")
def test_default(): ff = FFmpeg() assert ff._cmd == ['ffmpeg']
import os from ffmpy import FFmpeg print('Please enter the path') path = input('Path:') for root, dirs, files in os.walk(path): for file in files: if file.endswith('flac') or file.endswith('wav'): target_path = os.path.join(root, file) target_folder = os.path.dirname(target_path) target_base = os.path.basename(target_path) target_file_name = target_base.split('.')[0] print('Folder name:', target_folder) print('Base name:', target_base) print('Ready to convert..') convert_output_path = target_folder + '/' + target_file_name + '.mp3' ff = FFmpeg(inputs={target_path: None}, outputs={convert_output_path: '-q:a 0'}) ff.run() print('OK:', convert_output_path)
# ffmpeg stuff if VCODEC == 'gif': # if making a GIF, make the palette first. palette = p + "_palette.png" if scale == '': print("You must specify a width or height when making a GIF.") continue scalefilter = scale[4:] # 'scale=192:108' etc filters = 'fps={0},{1}:flags=lanczos'.format(str(FPS), scalefilter) ff = FFmpeg(global_options=[loglevel], inputs={inputpath: None}, outputs={ palette: '-y -vf "{filters},palettegen"'.format(filters=filters) }) print(ff.cmd) ff.run() # now make the gif from collections import OrderedDict inputs = OrderedDict([(inputpath, None), (palette, None)]) ff = FFmpeg(global_options=[loglevel, overwrite], inputs=inputs, outputs={ output: '-lavfi {filters} [x]; [x][1:v] paletteuse'.format( filters=filters) })
print('receiving data...') data = s.recv(1024) print('data=%s', (data)) if not data: break # write data to a file f.write(data) f.close() print('Successfully get the file') s.close() print('connection closed') # here we will implement ffmpeg ff = FFmpeg(inputs={'input.mp4': None}, outputs={'output.mp4': '-filter:v scale=960:-1 -c:a copy '}) ff.run() print('transfering file to client') t = socket.socket() t.bind(('127.0.0.2', 5000)) # Bind to the port t.listen(5) # Now wait for client connection. print('transcoder listening....') while True: conn, addr = t.accept() # Establish connection with client. print('Got connection from', addr) data = conn.recv(1024) print('Server received', repr(data))
def pcm2wav(path, extension): ff = FFmpeg( inputs={path: ['-f', 's16le', '-ar', '16000', '-ac', '2']}, outputs={''.join([path, extension]): '-y'}) ff.run()
def channel_tran(audio_file): new_audio_file = audio_file.replace('.wav', '-1chan.wav') ff = FFmpeg(inputs={audio_file: '-y'}, outputs={new_audio_file: '-ac 1'}) #print(ff.cmd) ff.run() return new_audio_file
from ffmpy import FFmpeg ff = FFmpeg( inputs={'IMG_0827.mp4': None}, outputs={"Icons/Thumbnail.png": ['-ss', '00:00:4', '-vframes', '1']}) print(ff.cmd) # Print result # ffmpeg -i input.mp4 -ss 00:00:10 -vframes 1 output.png ff.run()
def ff_convert(inputs, outputs): ff = FFmpeg(inputs=inputs, outputs=outputs) if log_mode == "debug": print ff.cmd ff.run()
sys.exit([1]) ### FOLDER SET UP, DIRECTORIES FOR FLAC OUTPUT. if not (os.path.exists(dir1)): os.makedirs(dir1) if not (os.path.exists(os.path.join(dir1,dir2))): os.makedirs(os.path.join(dir1,dir2)) if not (os.path.exists(os.path.join(dir1,dir2,dir3))): os.makedirs(os.path.join(dir1,dir2,dir3)) output_dir = os.path.join(dir1,dir2,dir3) output_file = os.path.join(output_dir,output_name+output_file_type) full_out_path = os.path.join(output_dir,output_file) ### CONVERSION if not (os.path.exists(output_file)): ff = FFmpeg( executable="C:/Users/Filippo/Documents/ffmpeg-20170520-64ea4d1-win64-static/bin/ffmpeg.exe",global_options="-y",inputs={wav_full_dir: None}, outputs={output_file:None}) ff.cmd ff.run() ## FLAC TAG WRITTING flac = fl(output_file) flac["year"] = id3_tags['Year'] flac["title"] = id3_tags['Title'] flac["artist"] = id3_tags['Artist'] flac["album"] = id3_tags['Album'] flac["genre"] = id3_tags['Genre'] if album_art_dir: art = pic() art.type = 3 with open(album_art_dir, 'rb') as f: art.data = f.read()
def test_output_options_list(): ff = FFmpeg(outputs={'/tmp/video.mp4': ['-f', 'mp4']}) assert ff._cmd == ['ffmpeg', '-f', 'mp4', '/tmp/video.mp4']
def test_output_options(output_options): ff = FFmpeg(outputs={'/tmp/rawvideo': output_options}) assert ff._cmd == [ 'ffmpeg', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s:v', '640x480', '/tmp/rawvideo' ] assert ff.cmd == 'ffmpeg -f rawvideo -pix_fmt rgb24 -s:v 640x480 /tmp/rawvideo'
def test_input_none(): ff = FFmpeg(inputs={None: ['-f', 'rawvideo']}) assert ff._cmd == ['ffmpeg', '-f', 'rawvideo']
def recThreaded(info): cmd = info[0] sock = info[2] filepath = info[3] filename = '' writer = None datetimenow = datetime.datetime.now() if (cmd["dir"] == 'out'): filename = (cmd["dir"] + '_' + cmd["local_number"] + '_' + cmd["remote_number"] + '_' + cmd["device"] + '_' + datetimenow.strftime('%Y-%m-%d_%H_%M_%S') + '.wav') else: filename = (cmd["dir"] + '_' + cmd["remote_number"] + '_' + cmd["local_number"] + '_' + cmd["device"] + '_' + datetimenow.strftime('%Y-%m-%d_%H_%M_%S') + '.wav') if (platform.system() == 'Windows'): filepath = filepath + '\\' + datetimenow.strftime('%Y-%m-%d') if (not os.path.exists(filepath)): os.makedirs(filepath) filepath = filepath + '\\' + filename else: filepath = filepath + '/' + datetimenow.strftime('%Y-%m-%d') if (not os.path.exists(filepath)): os.makedirs(filepath) filepath = filepath + '/' + filename if (cmd["codec"] == 'PCMU' or cmd["codec"] == 'PCMA'): # f = open(filepath, 'wb') writer = wave.open(filepath, 'wb') writer.setparams((1, 2, 8000, 8000 * 1, 'NONE', 'not compressed')) else: codec = cmd["codec"].lower() ar = None if (codec == 'g723'): codec = codec + '_1' elif ('g726' in codec): if (sys.byteorder == 'little'): codec = 'g726le' else: codec = 'g726' # command = ['ffmpeg' # , '-f', codec # , '-ar', '6k' # , '-ac', '1' # , '-i', '-' # , '-ar', '8k' # , '-ac', '1' # , '-acodec' # , 'pcm_s16le' # , filepath] # writer = sb.Popen(command, stdin=sb.PIPE) writer = wave.open(filepath, 'wb') writer.setparams((1, 2, 8000, 8000 * 1, 'NONE', 'not compressed')) ff = FFmpeg(inputs={'pipe:0': 'f=g722 ac=1'}, outputs={'pipe:1': 'ar=8k ac=1 acodec=pcm_s16le'}) print(str(ff)) while not info[1]: try: data = sock.recv(1024) # print(str(len(data))) if (cmd["codec"] == 'PCMU'): # f.write(data[12:]) writer.writeframes(audioop.ulaw2lin(data[12:], 2)) elif (cmd["codec"] == 'PCMA'): # f.write(data[12:]) writer.writeframes(audioop.alaw2lin(data[12:], 2)) elif (cmd["codec"].lower() == 'g722'): # writer.stdin.write(data[12:]) stdout, stderr = ff.run(input_data=data[12:], stdout=sb.PIPE) writer.writeframes(stdout, 2) print('CODEC2: ' + cmd["codec"]) else: # writer.stdin.write(data[12:]) continue except OSError as e: if (e.errno == 10038): # if (f is not None): # f.close() if (writer is not None): try: # if (writer.stdin is not None): # writer.stdin.close() # writer.wait() pass except: writer.close() print("UDP terminated: {0} / {1}".format(e.errno, e.strerror)) print("UDP terminated normally.") break else: print("recThreaded errno: {0} / {1}".format( e.errno, e.strerror)) continue # if (f is not None): # f.close() if (writer is not None): try: # if (writer.stdin is not None): # writer.stdin.close() # writer.wait() pass except: writer.close() if (sock is not None): sock.close() print("Recorder Thread Terminated..." + str(info[0]))
def test_global_options(global_options): ff = FFmpeg(global_options=global_options) assert ff._cmd == ['ffmpeg', '-hide_banner', '-y', '-v', 'debug'] assert ff.cmd == 'ffmpeg -hide_banner -y -v debug'
def video_clip(request): '''This is the Video Split Function''' short_url = request.session.get('uploaded_file_url') cut_url = short_url[1:] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, '').replace('\\', '/') full_url = MEDIA_ROOT[2:] + cut_url output_url = (MEDIA_ROOT + cut_url)[:-4] + '.flac' ve = FFmpeg( inputs={full_url: None}, outputs={output_url: ['-y', '-f', 'flac', '-ab', '192000', '-vn']}) # print(ve.cmd) ve.run() '''This is the Transcription Function''' tr = open("output.json", "w+") audio_url = open(output_url, "rb") response = requests.post( "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?timestamps=true", auth=("f7c2c504-fa84-4134-bf08-916409f4d53a", "3STmtCX6PaUM"), headers={"Content-Type": "audio/flac"}, data=audio_url) tr.write(response.text) # print("\nResponse is\n" + response.text + "\nAudio_url=" + str(output_url)) tr.close() '''This is the Extract Text Function''' data = json.load(open('output.json')) et = open("sentences.txt", "w+") for alt_result in data["results"]: for transcription in alt_result["alternatives"]: # By substituting fullstops with a space it prevents unexpected end of sentence when summarizing # print(transcription["transcript"]) nstr = re.sub(r'[.]', r'', transcription["transcript"]) et.write(nstr + '.\n') et.close() sample = open('sentences.txt').read() stop_words = set(open('resources/stopwords.txt').read().split()) f = open("summary.txt", "w+") caps = "([A-Z])" prefixes = "(Mr|St|Mrs|Ms|Dr)[.]" suffixes = "(Inc|Ltd|Jr|Sr|Co)" starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)" acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)" websites = "[.](com|net|org|io|gov)" def get_sentences(text): text = " " + text + " " text = text.replace("\n", " ") text = re.sub(prefixes, "\\1<prd>", text) text = re.sub(websites, "<prd>\\1", text) if "Ph.D" in text: text = text.replace("Ph.D.", "Ph<prd>D<prd>") text = re.sub("\s" + caps + "[.] ", " \\1<prd> ", text) text = re.sub(acronyms + " " + starters, "\\1<stop> \\2", text) text = re.sub(caps + "[.]" + caps + "[.]" + caps + "[.]", "\\1<prd>\\2<prd>\\3<prd>", text) text = re.sub(caps + "[.]" + caps + "[.]", "\\1<prd>\\2<prd>", text) text = re.sub(" " + suffixes + "[.] " + starters, " \\1<stop> \\2", text) text = re.sub(" " + suffixes + "[.]", " \\1<prd>", text) text = re.sub(" " + caps + "[.]", " \\1<prd>", text) if "\"" in text: text = text.replace(".\"", "\".") if "!" in text: text = text.replace("!\"", "\"!") if "?" in text: text = text.replace("?\"", "\"?") text = text.replace(".", ".<stop>") text = text.replace("?", "?<stop>") text = text.replace("!", "!<stop>") text = text.replace("<prd>", ".") sentences = text.split("<stop>") sentences = sentences[:-1] sentences = [s.strip() for s in sentences] return sentences def get_score(sentence, word_scores): score = 0 words = sentence.split() for word in words: if word not in stop_words: score += word_scores[word] return score word_scores = wordcount.get_word_frequency(sample, stop_words) sentences = get_sentences(sample) scores = {} for indx, sentence in enumerate(sentences): scores[sentence] = get_score(sentence, word_scores) sorted_scores = list(scores.values()) sorted_scores.sort() n = int(round(0.5 * sorted_scores.__len__() + 0.5)) cutoff = sorted_scores[n - 1] for sentence in sentences: if scores[sentence] > cutoff: # print(sentence) f.write(sentence + '\n') f.close() summryText = open("summary.txt", "r") def similar(a, b): return SequenceMatcher(None, a, b).ratio() the_final_mp4 = '' timegroup = [] timecrop = [] concat_list = [] all_lines = [] count = 0 for s in summryText: print(s) all_lines.append(s) for alt_result in data['results']: # print(alt_result) for transcription in alt_result["alternatives"]: # print(similar(s, transcription["transcript"])) if similar(s, transcription["transcript"]) >= 0.99: # print(transcription["transcript"]) timegroup = transcription["timestamps"] # print(timegroup) startwords = timegroup[0] endwords = timegroup[-1] # print(startwords) # print(endwords) starttimes = math.trunc((startwords[1:])[0]) endtimes = math.ceil((endwords[1:])[1]) # print(starttimes, endtimes) addtimes = endtimes - starttimes startHour = str(datetime.timedelta(seconds=starttimes)) endHour = str(datetime.timedelta(seconds=endtimes)) addHour = str(datetime.timedelta(seconds=addtimes)) print(startHour, endHour, addHour) count = count + 1 # Split the video using the timestamps ff = FFmpeg(inputs={full_url: None}, outputs={ 'cut/part' + str(count) + '.ts': [ '-y', '-ss', startHour, '-t', addHour, '-async', '1', '-strict', '-2' ] }) ff.run() # Merge all cut parts of video together concat = 'concat:cut/part' + str(count) + '.ts|' concat_list.append(concat) # print (concat_list) shortnote_ts = os.path.join(BASE_DIR, '').replace( '\\', '/') + "media/output.ts" fm = FFmpeg( inputs={"".join(concat_list): None}, outputs={shortnote_ts: ['-y', '-codec', 'copy']}) fm.run() shortnote_ts_url = shortnote_ts shortnote_mp4 = shortnote_ts_url[:-3] + ".mp4" vt = FFmpeg( inputs={shortnote_ts_url: None}, outputs={ shortnote_mp4: ['-y', '-c:v', 'libx264', '-preset', 'medium', '-crf', '0'] }) vt.run() cut_len = len(" /media/output.ts") shortnote_mp4 = shortnote_mp4[-cut_len:] the_final_mp4 = shortnote_mp4 print(shortnote_mp4) all_lines = "\n".join(all_lines) return render( request, 'uploads/summary.html', { 'uploaded_file_url': short_url, 'audio_url': output_url, 'the_final_mp4': the_final_mp4, 'all_lines': all_lines })
from ffmpy import FFmpeg import sys inputFile = "/Volumes/SanDisk/downloaded_programs/11440971_为什么性骚扰叫「咸猪手」?_字媒体_历史人文_1" outputFile = "/Volumes/SanDisk/11440971_为什么性骚扰叫「咸猪手」?_字媒体_历史人文.wav" ffmpeg = FFmpeg(inputs={inputFile: None}, outputs={outputFile: "-f wav -y"}) ffmpeg.run()
host = '127.0.0.1' # Get local machine name s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while True: filename = 'data/result/con'+str(count)+'.ts' newfilename = 'data/result/con'+str(count)+'.mp4' check = os.path.isfile(filename) if check: fileinfo = os.stat(filename) # print("filecount ",filecount) if (fileinfo.st_size != 0): arrival_time = time.time() count += 1 ff = FFmpeg( inputs={filename: None}, outputs={newfilename: ' -c copy'} ) print(ff) try: ff.run() except Exception: print('exception for ',count) pass departure_time = time.time() latency.append(departure_time - arrival_time) os.remove(filename) val = subprocess.check_output(cmd, shell=True); strval = val.decode('ASCII') strval = strval.replace('%CPU', '') print("strval ", strval)
def _download(self, track: Track) -> dict: status = {'track': track, 'returncode': -1} extractor = 'ytsearch' query = f'{extractor}:{str(track)} audio' output = self.path_holder.get_download_dir( ) / f'{_sort_dir(track, self.group)}' / safe_path_string( f'{str(track)}.{self.download_format}') output_temp = f'{str(self.path_holder.get_temp_dir())}/{track.id}.%(ext)s' if check_file(output): self.logger.info( f'{str(track)} -> is already downloaded. Skipping...') status['returncode'] = 0 return status create_dir(output.parent) options = { 'format': 'bestaudio/best', 'outtmpl': output_temp, 'restrictfilenames': True, 'ignoreerrors': True, 'nooverwrites': True, 'noplaylist': True, 'prefer_ffmpeg': True, 'logger': self.logger, 'progress_hooks': [_progress], 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': self.download_format, 'preferredquality': self.quality, }], 'postprocessor_args': [ '-write_id3v1', '1', '-id3v2_version', '3', '-metadata', f'title={track.name}', '-metadata', f'album={track.album_name}', '-metadata', f'date={track.release_date}', '-metadata', f'artist={", ".join(track.artist_names)}', '-metadata', f'disc={track.disc_number}', '-metadata', f'track={track.track_number}/{track.album_track_count}', ], **self.ydl_options, } output_temp = output_temp.replace('%(ext)s', self.download_format) if self.download_format == Format.MP3: options['postprocessor_args'].append('-codec:a') options['postprocessor_args'].append('libmp3lame') if self.ffmpeg_location != 'ffmpeg': options['ffmpeg_location'] = self.ffmpeg_location attempt = 0 downloaded = False while not downloaded: attempt += 1 try: with YoutubeDL(options) as ydl: ydl.download([query]) if check_file(Path(output_temp)): downloaded = True except YoutubeDlExtractionError as ex: if attempt > self.retry: status['returncode'] = 1 status['error'] = "Failed to download song." self.logger.error(ex.message) return status from shutil import move, Error as ShutilError if self.download_format != Format.MP3 or self.skip_cover_art: try: move(output_temp, output) except ShutilError: status['returncode'] = 1 status['error'] = 'Filesystem error.' self.logger.error('Failed to move temp file!') return status status['returncode'] = 0 self.logger.info(f'Downloaded -> {str(track)}') return status attempt = 0 added_artwork = False while not added_artwork: attempt += 1 cover_art_name = f'{track.album_name} - {track.artist_names[0]}' if cover_art_name in self.downloaded_cover_art: cover_art = self.downloaded_cover_art[cover_art_name] else: cover_art = self.path_holder.download_file(track.cover_art_url, extension='jpg') self.downloaded_cover_art[cover_art_name] = cover_art ffmpeg = FFmpeg( executable=self.ffmpeg_location, inputs={ str(output_temp): None, str(cover_art): None, }, outputs={ str(output): '-loglevel quiet -hide_banner -y -map 0:0 -map 1:0 -c copy -id3v2_version 3 ' '-metadata:s:v title="Album cover" -metadata:s:v comment="Cover (front)" ' # '-af "silenceremove=start_periods=1:start_duration=1:start_threshold=-60dB:' # 'detection=peak,aformat=dblp,areverse,silenceremove=start_periods=1:' # 'start_duration=1:start_threshold=-60dB:' # 'detection=peak,aformat=dblp,areverse"' }) try: ffmpeg.run() added_artwork = True except FFRuntimeError: if attempt > self.retry: try: move(output_temp, output) added_artwork = True except ShutilError: status['returncode'] = 1 status['error'] = 'Filesystem error.' self.logger.error('Failed to move temp file!') return status status['returncode'] = 0 try: from os import remove remove(output_temp) except OSError: pass self.logger.info(f'Downloaded -> {str(track)}') return status
def test_global_options_str(): ff = FFmpeg(global_options='-hide_banner -y') assert ff._cmd == ['ffmpeg', '-hide_banner', '-y']
verse_position = np.add(name_position, verse_offset) # draw the message on the background draw.text(name_position, name, fill=text_color, font=name_font) draw.text(verse_position, verse, fill=text_color, font=verse_font) # save the edited image intro_file_pic = 'intro.png' intropic.save(intro_file_pic) intro_file_vid = 'intro.mp4' if not exists(intro_file_vid): intro = FFmpeg(executable="./ffmpeg", inputs={intro_file_pic: '-loop 1 -t ' + str(intro_length)}, outputs={intro_file_vid: '-y -vf fps=29.97 -crf 0'}) intro.run() ###################### END OF INTRO ################################### # VIDEO SECTION: # output_opts = '-y -vf scale=' + resolution + ',fps=' + str(fps) # output_opts = '-filter_complex "gltransition=duration=1:offset=2:source=fade.glsl " -y' output_opts = '-y -an \ -filter_complex "\ [0:v]trim=start=0:end=' + str(round( intro_length - overlay, 2)) + ',setpts=PTS-STARTPTS[firstclip]; \ [1:v]colorbalance=bs=.3:rh=0.3[corrected]; \
def test_global_options_list(): ff = FFmpeg(global_options=['-hide_banner', '-y']) assert ff._cmd == ['ffmpeg', '-hide_banner', '-y']
return args if __name__ == '__main__': args = _parse_args() print(args) inputvid = 'test.mp4' basename = os.path.basename(inputvid) base, ext = os.path.splitext(basename) if DEMUX: ff = FFmpeg(inputs={inputvid: None}, outputs={ base + '-video.mp4': ['-map', '0:0', '-c:a', 'copy', '-f', 'mp4', '-y'], base + '-audio.mp4': ['-map', '0:1', '-c:a', 'copy', '-f', 'mp4', '-y'] }) print(ff.cmd) ff.run() wavefile = base + '.wav' if EXTRACTWAV: ff = FFmpeg(inputs={inputvid: None}, outputs={ wavefile: [ '-vn', '-acodec', 'pcm_s16le', '-ar', '44100', '-ac', '2', '-y' ]
def test_input_options_list(): ff = FFmpeg(inputs={'/tmp/rawvideo': ['-f', 'rawvideo']}) assert ff._cmd == ['ffmpeg', '-f', 'rawvideo', '-i', '/tmp/rawvideo']
s = socket.socket() # Create a socket object host = "127.0.0.2" #Ip address that the TCPServer is there port = 5000 # Reserve a port for your service every new transfer wants a new port or you must wait. s.connect((host, port)) s.send(b'Hello transcoder from client!') # filename = s.recv(16) # filename = s.recv(filename) with open('final.mp4', 'wb') as f: print ('file opened') while True: print('receiving data...') data = s.recv(1024) print('data=%s', (data)) if not data: break # write data to a file f.write(data) f.close() print('Successfully got the file') s.close() print('connection closed') # here we will implement ffmpeg ff = FFmpeg( inputs={'final.mp4': None} ) ff.run()
def convert_to_mp4(self, old, new): ff = FFmpeg(inputs={old: None}, outputs={new: '-y'}) ff.run()