animatedaliensfans's picture
Create app.py
94cbe98 verified
import os
import sounddevice as sd
import numpy as np
import wave
from moviepy.editor import VideoFileClip, AudioFileClip
def record_audio(output_path, duration=10, fs=44100):
"""
Records audio for a specified duration and saves it to the given output path.
"""
print(f"Recording audio... (Press Ctrl+C to stop)")
# Record audio
try:
audio_data = sd.rec(int(duration * fs), samplerate=fs, channels=2, dtype='float64')
sd.wait() # Wait until recording is finished
print("Recording finished.")
# Save audio as a .wav file
with wave.open(output_path, 'wb') as wf:
wf.setnchannels(2)
wf.setsampwidth(2) # 2 bytes for audio
wf.setframerate(fs)
wf.writeframes((audio_data * 32767).astype(np.int16).tobytes())
print(f"Audio saved to {output_path}")
except KeyboardInterrupt:
print("Recording interrupted.")
except Exception as e:
print(f"An error occurred during recording: {e}")
def dub_video(original_video_path, new_audio_path, output_video_path):
"""
Replaces the audio in the original video with the new audio.
"""
if not os.path.isfile(original_video_path):
print(f"Error: {original_video_path} does not exist.")
return
if not os.path.isfile(new_audio_path):
print(f"Error: {new_audio_path} does not exist.")
return
print("Dubbing the video...")
# Load video and new audio
video = VideoFileClip(original_video_path)
new_audio = AudioFileClip(new_audio_path)
# Set the new audio to the video
final_video = video.set_audio(new_audio)
# Write the output video file
final_video.write_videofile(output_video_path, codec='libx264')
print(f"Dubbing finished! Output saved at: {output_video_path}")
def main():
original_video_path = input("Enter the path to the original video file (e.g., video.mp4): ")
audio_output_path = "dubbed_audio.wav" # Temporary audio file
output_video_path = "dubbed_video.mp4" # Output video file
# Record new audio
duration = int(input("Enter the duration for the audio recording (in seconds): "))
record_audio(audio_output_path, duration)
# Dub the video
dub_video(original_video_path, audio_output_path, output_video_path)
if __name__ == "__main__":
main()