How to save audio file in Django by overriding save method?

时间:2018-04-20 01:01:22

标签: python django

I am trying to save audio file in my Django model by overriding save method. In my save method I am converting the text in audio using (Google Text to Speech) library. Here is the link to that Python Library GTTS
Here is my code:-

class Word(models.Model):
    word_vocab = models.CharField(max_length=200)
    audio = models.FileField(upload_to='audio/', blank=True)

    def save(self, *args, **kwargs):
        audio = gTTS(text=self.word_vocab, lang='en', slow=True)
        audio.save(self.word_vocab + ".mp3")
        self.audio.save(self.word_vocab + ".mp3", audio)
        super(Word, self).save(*args, **kwargs)

I can see that my audio file is getting created in Project's root folder but while saving it on the models audio field it's giving me the following error.
AttributeError: 'gTTS' object has no attribute 'read'
I have also tried using ContentFile like this

from django.core.files.base import ContentFile

In models save method:-

self.audio.save(self.word_vocab + ".mp3", ContentFile(audio)

But over here also I get the error:-

TypeError: a bytes-like object is required, not 'gTTS'

So I tried to convert it into bytes object:-

self.audio.save(self.word_vocab + ".mp3", ContentFile(bytes(audio)))

But still I ran into the following Error:-

TypeError: 'gTTS' object is not iterable

Also I would like to know if there is any other method to save the audio file for the corresponding text value like in our case "word" without having to save the audio file and then assign it to the model's audio field. I would like to directly save it to the models audio field.

Any help is much appreciated. Thanks in advance.

1 个答案:

答案 0 :(得分:1)

我强烈建议您将保存内的字段特定处理更改为自FileField范围内的自定义字段。问题是您正在尝试保存gTTS的实例。请尝试以下代码:

import tempfile

from django.core.files import File
from django.db import models


class Word(models.Model):
    word = models.CharField(max_length=200)
    audio = models.FileField(upload_to='audio/', blank=True)

    def save(self, *args, **kwargs):
        audio = gTTS(text=self.word_vocab, lang='en', slow=True)

        with tempfile.TemporaryFile(mode='w') as f:
            audio.write_to_fp(f)
            file_name = '{}.mp3'.format(self.word_vocab)
            self.audio.save(file_name, File(file=f))

        super(Word, self).save(*args, **kwargs)

函数audio.save(self.word_vocab + ".mp3")在您的用例中不起作用,您必须使用write_to_fp或打开此方法创建的文件,如文档中所述。我希望它有所帮助。