在Django中使用pydub合并wav文件,并将输出保存到模型FileField中

时间:2018-09-20 22:45:19

标签: django audio pydub

我使用自定义AudioInfo模型将.wav音频文件存储在Django数据库中,该模型具有以下参数:

1)“文本”(代表相应音频文件内容的字符串),例如“你好”

2)“音频”(相应的.wav音频文件),例如“ howdy.wav”

3)“持续时间(音频文件的持续时间),例如“ 0.7333”

models.py

class AudioInfoManager(models.Manager):

    def get_by_text(self, text):
        qs = self.get_queryset().filter(text=text) 
        if len(qs) == 0:
            return None
        return qs[0]

    def create_problem_audio(self, text, audio, duration):
        problem_audio = self.create(text=text, audio=audio, duration=duration)
        return problem_audio

class AudioInfo(models.Model):
    text        = models.TextField(unique=True)
    audio       = models.FileField(upload_to=upload_audio_info_path)
    duration    = models.FloatField()

    objects     = AudioInfoManager()

在我的views.py中,我想从AudioInfo模型中检索两个音频文件(例如“ howdy.wav”和“ partner.wav”),将这些文件合并为一个“ howdy_partner.wav”文件,并以“ info_problem_audio” AudioInfoManager方法的参数以创建新的AudioInfo实例并将其保存到数据库。请注意,我不想将新的“ howdy_partner.wav”文件导出到数据库中的任何位置。现在,这是我使用pydub软件包的尝试:

views.py

from .models import AudioInfo
from pydub import AudioSegment
from django.core.files.base import ContentFile

howdy_audio_info = AudioInfo.objects.get_by_text('howdy')
howdy_audio = howdy_audio_info.audio # .wav audio file that says "howdy"

partner_audio_info = AudioInfo.objects.get_by_text('partner')
partner_audio = partner_audio_info.audio # .wav audio file that says "partner"

# now I want to combine the two audio files to create a "howdy partner" audio file
howdy_audio_segment = AudioSegment.from_wav(howdy_audio)
partner_audio_segment = AudioSegment.from_wav(partner_audio)
howdy_partner_audio_segment = howdy_audio_segment + partner_audio_segment

# and then I want to save it to my AudioInfo model
# NOTE: this line fails because I can't generate a ContentFile using an AudioSegment
howdy_partner_audio = ContentFile(howdy_partner_audio_segment, 'howdy_partner.wav')
howdy_partner_audio_duration = howdy_partner_audio_segment.duration_seconds

howdy_partner_audio_info = AudioInfo.objects.create_problem_audio(
                               text="Howdy partner.",
                               audio=howdy_partner_audio, 
                               duration=howdy_partner_audio_duration
                           )

但是它失败了,因为我无法使用AudioSegment生成ContentFile(我相信我需要.wav格式的二进制数据)。我也尝试使用howdy_partner_audio_segment.raw_data,但这没有用,因为它只返回没有任何.wav格式的二进制字符串。在pydub文档中,它说我可以通过以下方式导出文件:

howdy_partner_audio_segment.export("howdy_partner.wav", format="wav")

但是我不想导出文件,我想将其保存为AudioInfo实例的字段。

0 个答案:

没有答案