ffmpeg.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. import tempfile
  3. import ffmpeg
  4. from .files import filename
  5. def get_audio(paths: list, audio_channel_index: int, sample_interval: list):
  6. temp_dir = tempfile.gettempdir()
  7. audio_paths = {}
  8. for path in paths:
  9. print(f"Extracting audio from {filename(path)}...")
  10. output_path = os.path.join(temp_dir, f"{filename(path)}.wav")
  11. ffmpeg_input_args = {}
  12. if sample_interval is not None:
  13. ffmpeg_input_args['ss'] = str(sample_interval[0])
  14. ffmpeg_output_args = {}
  15. ffmpeg_output_args['acodec'] = "pcm_s16le"
  16. ffmpeg_output_args['ac'] = "1"
  17. ffmpeg_output_args['ar'] = "16k"
  18. ffmpeg_output_args['map'] = "0:a:" + str(audio_channel_index)
  19. if sample_interval is not None:
  20. ffmpeg_output_args['t'] = str(
  21. sample_interval[1] - sample_interval[0])
  22. ffmpeg.input(path, **ffmpeg_input_args).output(
  23. output_path,
  24. **ffmpeg_output_args
  25. ).run(quiet=True, overwrite_output=True)
  26. audio_paths[path] = output_path
  27. return audio_paths
  28. def add_subtitles_to_mp4(subtitles: dict):
  29. input_file = list(subtitles.keys())[0]
  30. subtitle_file = subtitles[input_file]
  31. output_file = input_file
  32. os.rename(input_file, input_file+'_edit')
  33. input_stream = ffmpeg.input(input_file+'_edit')
  34. subtitle_stream = ffmpeg.input(subtitle_file)
  35. # Combine input video and subtitle
  36. output = ffmpeg.output(input_stream, subtitle_stream, output_file.replace('.mkv','.mp4'), c='copy', **{'c:s': 'mov_text'}, **{'metadata:s:s:0': 'language=eng'})
  37. ffmpeg.run(output, quiet=True, overwrite_output=True)
  38. os.remove(input_file+'_edit')
  39. # remove tempfiles
  40. os.remove(subtitle_file)
  41. os.remove(subtitle_file.replace(".srt",".wav"))