Merge pull request #69 from chappjo/patch-1

Make audio transfer lossless
This commit is contained in:
hzwer
2020-12-14 16:09:20 +08:00
committed by GitHub

View File

@@ -14,26 +14,30 @@ warnings.filterwarnings("ignore")
def transferAudio(sourceVideo, targetVideo):
import shutil
import moviepy.editor
tempAudioFileName = "./temp/audio.mp3"
tempAudioFileName = "./temp/audio.mkv"
# split audio from original video file and store in "temp" directory
if True:
# extract audio from video
if True:
video = moviepy.editor.VideoFileClip(sourceVideo)
audio = video.audio
# clear old "temp" directory if it exits
if os.path.isdir("temp"):
# remove temp directory
shutil.rmtree("temp")
# create new "temp" directory
os.makedirs("temp")
# write audio file to "temp" directory
audio.write_audiofile(tempAudioFileName)
# extract audio from video
os.system("ffmpeg -y -i " + sourceVideo + " -c:a copy -vn " + tempAudioFileName)
os.rename(targetVideo, "noAudio_"+targetVideo)
# combine audio file and new video file
os.system("ffmpeg -y -i " + "noAudio_"+targetVideo + " -i " + tempAudioFileName + " -c copy " + targetVideo)
if os.path.getsize(targetVideo) == 0: # if ffmpeg failed to merge the video and audio together try converting the audio to mp3
tempAudioFileName = "./temp/audio.mp3"
os.system("ffmpeg -y -i " + sourceVideo + " -c:a mp3 -vn " + tempAudioFileName)
os.system("ffmpeg -y -i " + "noAudio_"+targetVideo + " -i " + tempAudioFileName + " -c copy " + targetVideo)
print("Lossless audio transfer failed. Audio was transcoded to mp3 instead.")
# remove audio-less video
os.remove("noAudio_"+targetVideo)