72 lines
2.7 KiB
Python
72 lines
2.7 KiB
Python
import os
|
|
|
|
from pydub import AudioSegment
|
|
|
|
from app.core._config import UPLOADS_DIR
|
|
from app.core.logger import make_log
|
|
import traceback
|
|
|
|
|
|
class AudioContentMixin:
|
|
def as_audio_segment(self) -> AudioSegment:
|
|
audio = None
|
|
open_log = f"StoredContent.as_audio_segment({self.id}): " + '\n'
|
|
file_ext = self.filename.split('.')[-1]
|
|
if not audio:
|
|
try:
|
|
if file_ext == 'mp3':
|
|
audio = AudioSegment.from_mp3(self.filepath)
|
|
elif file_ext == 'wav':
|
|
audio = AudioSegment.from_wav(self.filepath)
|
|
elif file_ext == 'ogg':
|
|
audio = AudioSegment.from_ogg(self.filepath)
|
|
elif file_ext == 'flv':
|
|
audio = AudioSegment.from_flv(self.filepath)
|
|
except BaseException as e:
|
|
open_log += f"Error loading audio from file (using encoding): {e}" + '\n' + traceback.format_exc()
|
|
|
|
if not audio:
|
|
try:
|
|
audio = AudioSegment.from_file(self.filepath)
|
|
except BaseException as e:
|
|
open_log += f"Error loading audio from file: {e}" + '\n' + traceback.format_exc()
|
|
|
|
if not audio:
|
|
try:
|
|
audio = AudioSegment(self.file_bin)
|
|
except BaseException as e:
|
|
open_log += f"Error loading audio from binary: {e}" + '\n' + traceback.format_exc()
|
|
|
|
make_log("Storage", open_log, level="debug")
|
|
assert audio, "Can't load audio as AudioSegment"
|
|
return audio
|
|
|
|
def as_mp3(self, seconds_limit=None):
|
|
tempfile_path = os.path.join(UPLOADS_DIR, f"temporary_{self.hash}.mp3")
|
|
audio = self.as_audio_segment()
|
|
if seconds_limit:
|
|
seconds_limit = int(seconds_limit)
|
|
tempfile_path += f"_f{seconds_limit}"
|
|
|
|
if not os.path.exists(tempfile_path):
|
|
try:
|
|
cover_content = self.__class__.from_cid(self.meta.get('cover_cid'))
|
|
cover_tempfile_path = cover_content.as_jpeg()
|
|
except BaseException as e:
|
|
make_log("Storage", f"Error getting cover content: {e}", level="debug")
|
|
cover_content = None
|
|
cover_tempfile_path = None
|
|
|
|
try:
|
|
audio = audio[:seconds_limit * 1000] if seconds_limit else audio
|
|
audio.export(tempfile_path, format="mp3", cover=cover_tempfile_path)
|
|
except BaseException as e:
|
|
make_log("Storage", f"Error converting audio: {e}" + '\n' + traceback.format_exc(), level="error")
|
|
|
|
assert os.path.exists(tempfile_path), "Can't convert audio to mp3"
|
|
|
|
return tempfile_path
|
|
|
|
|
|
|