【问题标题】:How do I get duration of an In Memory Video in Python / Django?如何在 Python / Django 中获取内存中视频的持续时间?
【发布时间】:2020-03-17 11:55:18
【问题描述】:

所以我成功地使用以下代码在 Django 中获取保存视频的持续时间。

def get_video_length(file_path):
command = [
    'ffprobe',
    '-v',
    'error',
    '-show_entries',
    'format=duration',
    '-of',
    'default=noprint_wrappers=1:nokey=1',
    file_path
  ]

try:
    output = check_output( command, stderr=STDOUT ).decode()
except CalledProcessError as e:
    output = e.output.decode()

return output

但现在我需要在保存之前获取上传文件的持续时间。 我有一个带有 FileField 的序列化程序,并且在验证方法上我应该检查视频持续时间。 例如:

class VideoSerializer(serializers.Serializer):
video = serializers.FileField(required=True, validators=[validate_media_extension, validate_video_duration])

然后在 validate_video_duration 上,我需要调用一些方法,例如 get_video_length,但我需要一个替代方法来从内存中的视频中获取持续时间。我拥有的对象是 InMemoryUploadedFile (https://docs.djangoproject.com/en/2.2/_modules/django/core/files/uploadedfile/) 的一个实例

【问题讨论】:

    标签: python django video ffmpeg ffprobe


    【解决方案1】:

    您应该能够将文件作为标准输入传递。

    def get_video_length(inmemory_file):
    
        command = [
            'ffprobe',
            '-v',
            'error',
            '-show_entries',
            'format=duration',
            '-of',
            'default=noprint_wrappers=1:nokey=1',
            '-'
          ]
    
        try:
            output = check_output(
                command,
                stdin=inmemory_file.open(),
                stderr=STDOUT
            ).decode()
        except CalledProcessError as e:
            output = e.output.decode()
    
        return output
    

    话虽如此,我希望视频文件太大而无法在内存中处理。

    【讨论】:

    • 那你建议我怎么做?序列化程序似乎已经暂时将文件留在内存中,保存到临时文件只是为了验证持续时间是否更好?基本上,我需要的是在服务器端上传视频并验证持续时间。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    相关资源
    最近更新 更多