def get_mime_type(filename):
""" Returns the MIME type associated with a particular audio file.
"""
try:
import magic
except ImportError:
if get_mime_type.warn:
logger.warning('Python package "magic" could not be loaded, '
'possibly because system library "libmagic" could not be '
'found. We are falling back on our own heuristics.')
get_mime_type.warn = False
ext = os.path.splitext(filename)[1].lower()
return {
'.wav' : 'audio/x-wav',
'.mp3' : 'audio/mpeg',
'.flac' : 'audio/x-flac'
}.get(ext, 'unknown')
else:
# Read off magic numbers and return MIME types
mime_magic = magic.Magic(mime=True)
ftype = mime_magic.from_file(filename)
if isinstance(ftype, bytes):
ftype = ftype.decode('utf-8')
# If we are dealing with a symlink, read the link
# and try again with the target file. We do this in
# a while loop to cover the case of symlinks which
# point to other symlinks
current_filename = filename
while ftype == 'inode/symlink':
current_filename = os.readlink(current_filename)
ftype = mime_magic.from_file(current_filename)
ftype = ftype.decode('utf-8') if isinstance(ftype, bytes) else ftype
return ftype
评论列表
文章目录