在保存 Django 之前如何将文件转换为 mp3?

How do I convert a file to mp3 before saving django?

我找到了一些关于扩展和更改模型上的 save() 函数的信息,但是其他一些人提到这样做是不好的做法,应该修改管理表单。任何帮助都会很棒,我一直在四处寻找并试图解决这个问题几个小时。谢谢。

我希望在保存文件之前执行此代码,将音频文件保存到模型文件字段

from moviepy.editor import *

audio = VideoFileClip("test-file.mp4").audio
audio.write_audiofile("audio.mp3")

好的,所以我自己解决了。我不知道这是执行此操作的正确方法还是安全方法,但它确实有效。任何 tips/suggestions 或更好的解决方案都会很棒。谢谢!

from django.db import models
from django.core.exceptions import ValidationError
from moviepy.editor import *

def update_filename(instance, filename):
    return filename[0:-4] + ".mp3"

def process_file(file):
    file_audio = VideoFileClip(file.temporary_file_path()).audio
    new_file_path = file.temporary_file_path()[:-4] + ".mp3"
    file_audio.write_audiofile(new_file_path)
    file.file.name = new_file_path

class Sermon(models.Model):
    date = models.DateField()
    audio = models.FileField(upload_to=update_filename)

    def clean(self):
        super().clean()
        extension = self.audio.name[len(self.audio.name) - 4:]
        file = self.audio.file
        file.__class__
        if extension != ".mp3" and extension != ".mp4":
            raise ValidationError("Warning Warning Warning")
        elif extension == ".mp4":
            process_file(file)