I have a rest API built with Django rest framework, one of its serializers is to accept Base64file which is our audio file, now what I want is simply check and validate the decoded file so I can know if this a valid mp4 or any audio type in general or not.
the problem is, sometimes the audio file after upload and save is corrupted and can't be played, so doing this validation is essential to make sure that the file is sent correctly or it was sent corrupted at first place.
I have been digging on google and the Internet searching for anything can do this simple task but all I found was how to play audio or manipulate it, I didn't even find something that may raise an exception if the file is not valid when trying to open it.
for more info. I'm using django-extra-fields, I use Base64FileField to implement my Audio file field, they provided an example to do so for like PDF's, I'm trying to do this similar way for audio but what is holding me is doing the check for audio.
The example of PDF:
class PDFBase64File(Base64FileField):
ALLOWED_TYPES = ['pdf']
def get_file_extension(self, filename, decoded_file):
try:
PyPDF2.PdfFileReader(io.BytesIO(decoded_file))
except PyPDF2.utils.PdfReadError as e:
logger.warning(e)
else:
return 'pdf'
What is done so far:
class AudioBase64File(Base64FileField):
ALLOWED_TYPES = (
'amr',
'ogg',
'm4a',
'3gp',
'aac',
'mp4',
'mp3',
'flac'
)
INVALID_FILE_MESSAGE = ("Please upload a valid audio.")
INVALID_TYPE_MESSAGE = ("The type of the audio couldn't be determined.")
def get_file_extension(self, filename, decoded_file):
# missing validation
return 'mp4'