Я работал над этим несколько дней, и все лучшие LLM потерпели неудачу, поэтому я считаю, что это отличный вопрос для SO.
Поэтому мой вопрос прост
У меня есть изображение A, оно в формате PNG
У меня есть аудио A, оно в формате MP3
У меня есть видео Б, которое может быть любого формата, разрешения, кодировки, звука и т. д.
Теперь я хочу превратить изображение A + аудио A в видео A с точными атрибутами видео B, чтобы я мог объединить их без кодирования< /p>
Вот мой код, который не работает. Я использую Python и последнюю версию FFMPEG с большинством кодеков и функций
def get_video_info(video_path):
cmd = [
FFPROBE_PATH,
'-v', 'quiet',
'-print_format', 'json',
'-show_format',
'-show_streams',
video_path
]
result = subprocess.run(cmd, capture_output=True, text=True)
info = json.loads(result.stdout)
video_stream = next((s for s in info['streams'] if s['codec_type'] == 'video'), None)
audio_stream = next((s for s in info['streams'] if s['codec_type'] == 'audio'), None)
if not video_stream or not audio_stream:
logging.error("Failed to find video or audio stream")
return None
return {
'width': int(video_stream.get('width', 0)),
'height': int(video_stream.get('height', 0)),
'fps': eval(video_stream.get('r_frame_rate', '30/1')),
'video_codec': video_stream.get('codec_name', ''),
'audio_codec': audio_stream.get('codec_name', ''),
'audio_sample_rate': int(audio_stream.get('sample_rate', 0)),
'audio_channels': audio_stream.get('channels', 0),
'pixel_format': video_stream.get('pix_fmt', ''),
'color_space': video_stream.get('color_space', ''),
'color_transfer': video_stream.get('color_transfer', ''),
'color_primaries': video_stream.get('color_primaries', ''),
}
def create_thumbnail_video(thumbnail_url, video_id, video_info, duration=40):
output_dir = os.path.abspath('downloads')
output_path = os.path.join(output_dir, f"{video_id}_thumbnail.mp4")
audio_path = os.path.abspath("a.mp3")
try:
# 1. Download and process the image
logging.info("Downloading thumbnail image...")
response = requests.get(thumbnail_url, timeout=30)
response.raise_for_status()
# Save the original image
original_image_path = os.path.join(output_dir, f'{video_id}_original_image.png')
with open(original_image_path, 'wb') as f:
f.write(response.content)
# 2. Open and resize the image
image = Image.open(original_image_path)
width, height = video_info['width'], video_info['height']
image = image.resize((width, height), Image.LANCZOS)
# Save resized image
resized_image_path = os.path.join(output_dir, f'{video_id}_resized_image.png')
image.save(resized_image_path, 'PNG')
# 3. Get properties of the main video using ffprobe
main_video_path = os.path.join(output_dir, f"{video_id}.mp4") # Assuming main video has .mp4 extension
main_video_info = get_video_info(main_video_path)
if not main_video_info:
raise Exception("Could not get information about the main video.")
# 4. Generate video with matching encoding
logging.info("Generating thumbnail video with matching codec and properties...")
ffmpeg_command = [
FFMPEG_PATH,
'-y',
'-loop', '1',
'-i', resized_image_path,
'-i', audio_path,
'-c:v', main_video_info['video_codec'],
'-c:a', main_video_info['audio_codec'],
'-ar', str(main_video_info['audio_sample_rate']),
'-pix_fmt', main_video_info['pixel_format'],
'-color_range', main_video_info.get('color_range', '1'), # Default to tv/mpeg (limited) if not found
'-colorspace', main_video_info['color_space'],
'-color_trc', main_video_info['color_transfer'],
'-color_primaries', main_video_info['color_primaries'],
'-vf', f"fps={main_video_info['fps']},scale={width}:{height}",
'-shortest',
'-t', str(duration),
output_path
]
subprocess.run(ffmpeg_command, check=True, capture_output=True, text=True)
logging.info(f"Thumbnail video created: {output_path}")
# 5. Clean up intermediate files
for file_path in [original_image_path, resized_image_path]:
if os.path.exists(file_path):
os.remove(file_path)
logging.info(f"Removed intermediate file: {file_path}")
return output_path
except requests.RequestException as e:
logging.error(f"Error downloading thumbnail: {e}")
except subprocess.CalledProcessError as e:
logging.error(f"FFmpeg error: {e.stderr}")
except Exception as e:
logging.error(f"Error in create_thumbnail_video: {e}")
logging.error(traceback.format_exc())
# If we've reached this point, an error occurred
logging.warning("Thumbnail video creation failed. Returning None.")
return None
Подробнее здесь: https://stackoverflow.com/questions/792 ... butes-of-v
Как превратить изображение A + аудио + A в видео A с теми же атрибутами, что и у видео B, чтобы их можно было объединить ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как транслировать видео и аудио с Raspi на веб -сайт и вернуть аудио [закрыто]
Anonymous » » в форуме Python - 0 Ответы
- 4 Просмотры
-
Последнее сообщение Anonymous
-