def save(self, *args, **kwargs): """Overriden save method to automatically convert the audio to an mp3""" duration = kwargs.pop('duration', None) needs_conversion = self.audio and not self.audio.name.lower().endswith( '.mp3') # If we have an audio file and it's not an mp3, make it one if duration or needs_conversion: if not os.path.exists(self.audio.path): # If it doesn't already exist, save the old audio first so that we can re-encode it # This is needed if it's newly uploaded self.audio.save(self.audio.name, File(self.audio), save=False) audio_helper = AudioHelper() if needs_conversion: mp3_filename = audio_helper.make_mp3(self.audio.path) mp3_file = open(mp3_filename, 'rb') self.audio.save(os.path.basename(mp3_file.name), File(mp3_file), save=False) if duration: self.audio_duration = audio_helper.get_audio_duration( self.audio.path) # Call the original model save to do everything super(AudioMP3Mixin, self).save(*args, **kwargs)
def forwards(self, orm): for recording in orm['speeches.Recording'].objects.all(): timestamps = recording.timestamps if timestamps.count(): recording.start_datetime = timestamps.all()[0].timestamp if recording.audio: audio_helper = AudioHelper() duration = audio_helper.get_audio_duration(recording.audio.path) recording.audio_duration = duration recording.save()
def create_or_update_speeches(self, instance): created_speeches = [] # Split the recording's audio files audio_helper = AudioHelper() audio_files = audio_helper.split_recording(self) sorted_timestamps = self.timestamps.order_by("timestamp") for index, audio_file in enumerate(audio_files): new = True speech = Speech( instance=instance, public=False, type='speech', ) timestamp = None if sorted_timestamps and len(sorted_timestamps) > 0: # We assume that the files are returned in order of timestamp timestamp = sorted_timestamps[index] if timestamp.speech: speech = timestamp.speech new = False try: speech.audio.delete(save=False) except: pass # shouldn't happen, but we're going to recreate anyway # so not critical speech.speaker = timestamp.speaker speech.start_date = timestamp.timestamp.date() speech.start_time = timestamp.timestamp.time() # If there's another one we can work out the end too if index < len(sorted_timestamps) - 1: next_timestamp = sorted_timestamps[index + 1] speech.end_date = next_timestamp.timestamp.date() speech.end_time = next_timestamp.timestamp.time() audio_file = open(audio_file, 'rb') speech.audio = File(audio_file, name=os.path.basename(audio_file.name)) speech.save() if new: created_speeches.append(speech) if timestamp: timestamp.speech = speech timestamp.save() return created_speeches
def check_audio_durations(recording, durations): audio_helper = AudioHelper() for (rt, d) in zip(recording.timestamps.all(), durations): self.assertEqual( audio_helper.get_audio_duration(rt.speech.audio.path), d)
def setUp(self): super(AudioHelperTests, self).setUp() self.helper = AudioHelper() self.tmp_filename = None self.remove_tmp_filename = False