def setUp(self): original = os.path.join(DATA_DIR, "adif.aac") self.filename = get_temp_copy(original) tag = ID3() tag.add(TIT1(text=[u"a" * 5000], encoding=3)) tag.save(self.filename) self.aac = AAC(original) self.aac_id3 = AAC(self.filename)
def setUp(self): original = os.path.join("tests", "data", "adif.aac") fd, self.filename = mkstemp(suffix='.aac') os.close(fd) shutil.copy(original, self.filename) tag = ID3() tag.add(TIT1(text=[u"a" * 5000], encoding=3)) tag.save(self.filename) self.aac = AAC(original) self.aac_id3 = AAC(self.filename)
def __init__(self, filename): with translate_errors(): audio = AAC(filename) self["~#length"] = audio.info.length self["~#bitrate"] = int(audio.info.bitrate / 1000) if audio.info.channels: self["~#channels"] = audio.info.channels self.sanitize(filename)
class TADTS(TestCase): def setUp(self): original = os.path.join("tests", "data", "empty.aac") fd, self.filename = mkstemp(suffix='.aac') os.close(fd) shutil.copy(original, self.filename) tag = ID3() tag.add(TIT1(text=[u"a" * 5000], encoding=3)) tag.save(self.filename) self.aac = AAC(original) self.aac_id3 = AAC(self.filename) def tearDown(self): os.remove(self.filename) def test_channels(self): self.failUnlessEqual(self.aac.info.channels, 2) self.failUnlessEqual(self.aac_id3.info.channels, 2) def test_bitrate(self): self.failUnlessEqual(self.aac.info.bitrate, 3159) self.failUnlessEqual(self.aac_id3.info.bitrate, 3159) def test_sample_rate(self): self.failUnlessEqual(self.aac.info.sample_rate, 44100) self.failUnlessEqual(self.aac_id3.info.sample_rate, 44100) def test_length(self): self.failUnlessAlmostEqual(self.aac.info.length, 3.70, 2) self.failUnlessAlmostEqual(self.aac_id3.info.length, 3.70, 2) def test_not_my_file(self): self.failUnlessRaises( AACError, AAC, os.path.join("tests", "data", "empty.ogg")) self.failUnlessRaises( AACError, AAC, os.path.join("tests", "data", "silence-44-s.mp3")) def test_pprint(self): self.assertEqual(self.aac.pprint(), self.aac_id3.pprint()) self.assertTrue("ADTS" in self.aac.pprint())
class TADIF(TestCase): def setUp(self): original = os.path.join(DATA_DIR, "adif.aac") self.filename = get_temp_copy(original) tag = ID3() tag.add(TIT1(text=[u"a" * 5000], encoding=3)) tag.save(self.filename) self.aac = AAC(original) self.aac_id3 = AAC(self.filename) def tearDown(self): os.remove(self.filename) def test_channels(self): self.failUnlessEqual(self.aac.info.channels, 2) self.failUnlessEqual(self.aac_id3.info.channels, 2) def test_bitrate(self): self.failUnlessEqual(self.aac.info.bitrate, 128000) self.failUnlessEqual(self.aac_id3.info.bitrate, 128000) def test_sample_rate(self): self.failUnlessEqual(self.aac.info.sample_rate, 48000) self.failUnlessEqual(self.aac_id3.info.sample_rate, 48000) def test_length(self): self.failUnlessAlmostEqual(self.aac.info.length, 0.25, 2) self.failUnlessAlmostEqual(self.aac_id3.info.length, 0.25, 2) def test_not_my_file(self): self.failUnlessRaises( AACError, AAC, os.path.join(DATA_DIR, "empty.ogg")) self.failUnlessRaises( AACError, AAC, os.path.join(DATA_DIR, "silence-44-s.mp3")) def test_pprint(self): self.assertEqual(self.aac.pprint(), self.aac_id3.pprint()) self.assertTrue("ADIF" in self.aac.pprint())
class TADIF(TestCase): def setUp(self): original = os.path.join(DATA_DIR, "adif.aac") self.filename = get_temp_copy(original) tag = ID3() tag.add(TIT1(text=[u"a" * 5000], encoding=3)) tag.save(self.filename) self.aac = AAC(original) self.aac_id3 = AAC(self.filename) def tearDown(self): os.remove(self.filename) def test_channels(self): self.failUnlessEqual(self.aac.info.channels, 2) self.failUnlessEqual(self.aac_id3.info.channels, 2) def test_bitrate(self): self.failUnlessEqual(self.aac.info.bitrate, 128000) self.failUnlessEqual(self.aac_id3.info.bitrate, 128000) def test_sample_rate(self): self.failUnlessEqual(self.aac.info.sample_rate, 48000) self.failUnlessEqual(self.aac_id3.info.sample_rate, 48000) def test_length(self): self.failUnlessAlmostEqual(self.aac.info.length, 0.25, 2) self.failUnlessAlmostEqual(self.aac_id3.info.length, 0.25, 2) def test_not_my_file(self): self.failUnlessRaises(AACError, AAC, os.path.join(DATA_DIR, "empty.ogg")) self.failUnlessRaises(AACError, AAC, os.path.join(DATA_DIR, "silence-44-s.mp3")) def test_pprint(self): self.assertEqual(self.aac.pprint(), self.aac_id3.pprint()) self.assertTrue("ADIF" in self.aac.pprint())
def audioFile(audio): aud_str = str(audio) if aud_str.endswith(".mp3"): aud1 = MP3(audio) len1 = aud1.info.length return int(len1) elif aud_str.endswith('.wav'): aud2 = WAVE(audio) len2 = aud2.info.length return int(len2) elif aud_str.endswith('.flac'): aud3 = FLAC(audio) len3 = aud3.info.length return int(len3) elif aud_str.endswith('.aac'): aud4 = AAC(audio) len4 = aud4.info.length return int(len4) elif aud_str.endswith('.ac3'): aud5 = AC3(audio) len5 = aud5.info.length return int(len5) elif aud_str.endswith('.aiff'): aud6 = AIFF(audio) len6 = aud6.info.length return int(len6) elif aud_str.endswith('.asf'): aud7 = ASF(audio) len7 = aud7.info.length return int(len7) elif aud_str.endswith('.dsf'): aud8 = DSF(audio) len8 = aud8.info.length return int(len8) elif aud_str.endswith('.mp4'): aud9 = MP4(audio) len9 = aud9.info.length return int(len9) elif aud_str.endswith('.smf'): aud10 = SMF(audio) len10 = aud10.info.length return int(len10) elif aud_str.endswith('.ogg'): aud12 = OggFileType(audio) len12 = aud12.info.length return int(len12) else: return str("File type not supported.")
def getAudioMetaData(service, ext): title = "" genre = "" artist = "" album = "" length = "" audio = None if fileExists("/tmp/.emcAudioTag.jpg"): os.remove("/tmp/.emcAudioTag.jpg") elif fileExists("/tmp/.emcAudioTag.png"): os.remove("/tmp/.emcAudioTag.png") elif fileExists("/tmp/.emcAudioTag.gif"): os.remove("/tmp/.emcAudioTag.gif") if service: path = service.getPath() if ext.lower() == ".mp3": try: audio = MP3(os.path.join(path), ID3 = EasyID3) except: audio = None elif ext.lower() == ".flac": try: audio = FLAC(os.path.join(path)) except: audio = None elif ext.lower() == ".ogg": try: audio = OggVorbis(os.path.join(path)) except: audio = None elif ext.lower() == ".mp4" or ext.lower() == ".m4a": try: audio = EasyMP4(os.path.join(path)) except: audio = None # first for older mutagen-package(under 1.27) # APEv2 is tagged from tools like "mp3tag" # no tagging in new mutagen.aac elif ext.lower() == ".aac": try: audio = APEv2File(os.path.join(path)) except: audio = None if audio: if ext.lower() != ".aac": length = str(datetime.timedelta(seconds=int(audio.info.length))) else: if isMutagenAAC: getlength = AAC(os.path.join(path)) length = str(datetime.timedelta(seconds=int(getlength.info.length))) else: length = str(datetime.timedelta(seconds=int(audio._Info.length))) title = audio.get('title', [service.getPath()])[0] try: genre = audio.get('genre', [''])[0] except: genre = "" artist = audio.get('artist', [''])[0] album = audio.get('album', [''])[0] # now we try to get embedded covers if ext.lower() == ".mp3": try: scover = ID3(service.getPath()) except: scover = None if scover: scovers = scover.getall("APIC") if len(scovers) > 0: try: ext = "." + scovers[0].mime.lower().split("/", -1)[1] writeTmpCover(scovers[0].data, ext) except Exception, e: emcDebugOut("[EMCMutagenSupport] Exception in Mp3EmbeddedCover: " + str(e)) elif ext.lower() == ".flac": try: scover = audio.pictures except: scover = None if scover: if scover[0].data: try: ext = "." + scover[0].mime.lower().split("/", -1)[1] writeTmpCover(scover[0].data, ext) except Exception, e: emcDebugOut("[EMCMutagenSupport] Exception in FlacEmbeddedCover: " + str(e)) elif ext.lower() == ".ogg": try: scover = audio except: scover = None if scover: for b64_data in scover.get("metadata_block_picture", []): try: data = base64.b64decode(b64_data) except (TypeError, ValueError): continue try: picture = Picture(data) except FLACError: continue try: ext = "." + picture.mime.lower().split("/", -1)[1] writeTmpCover(picture.data, ext) except Exception, e: emcDebugOut("[EMCMutagenSupport] Exception in OggEmbeddedCover: " + str(e))
def __init__(self, filename): audio = AAC(filename) self["~#length"] = audio.info.length self["~#bitrate"] = int(audio.info.bitrate / 1000) self.sanitize(filename)
def main(): root_name = '_wm_npr_one_' parser = argparse.ArgumentParser(description='NPR One gathering app for offline use.', epilog='more info/coffee tip at github/watermoccasin') parser.add_argument('media', default='D:\\', help='path to store media') parser.add_argument('-w', '--workout', nargs='?', default=30, type=int, help='length of workout in minutes') parser.add_argument('-s', '--speedup', nargs='?', const=2.0, type=float, help='speed up playback by factor (Default is 200%)') parser.add_argument("-l", "--log", dest="logLevel", nargs='?', const='INFO', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help="Set the logging level") parser.add_argument('-v', '--verbose', help="increase output verbosity", action="store_true") args = parser.parse_args() dir = args.media if args.verbose: logging.basicConfig(level=logging.DEBUG) elif args.logLevel: logging.basicConfig(filename=os.path.join(dir, 'water_moccasin.log'),level=args.logLevel) # check media path ok first if (not os.access(dir, os.W_OK)): logging.warning('Media {0} not available.'.format(dir)) exit() workout_length = args.workout * 60 logging.info('workout length (in seconds): {0}'.format(workout_length)) # clean up old media files = os.listdir(dir) for file in files: if root_name in file and file.endswith(".mp3"): os.remove(os.path.join(dir,file)) time_length = track_count = 0 npr.login() player = npr.One() while time_length < workout_length: track_count += 1 path = urllib.parse.urlparse(player.audio).path name = os.path.splitext(os.path.basename(path))[0] + '.mp3' ext = os.path.splitext(path)[1] response = get(player.audio) fn = tempfile.NamedTemporaryFile(delete=False, suffix=ext) fn.close() fn = fn.name file = tempfile.NamedTemporaryFile(delete=False, suffix=ext, mode='w+b') fn_orig = file.name logging.debug(fn_orig) file.write(response.content) file.close() speedup_cmd = '' if args.speedup: speedup_cmd = ' -filter:a "atempo={0}" '.format(args.speedup) conversion_command = 'ffmpeg -y -i {0} {1} -vn "{2}"'.format(fn_orig, speedup_cmd, fn) logging.info(conversion_command) with open(os.devnull, 'rb') as devnull: p = subprocess.Popen(conversion_command, stdin=devnull, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p_out = p.communicate() logging.debug(p_out, time_length) sound = AudioSegment.from_file(fn).export(os.path.join(dir, '{0:02}{1}{2}'.format(track_count, root_name, name)), format="mp3") player.skip() if ext=='.mp3': audio = MP3(fn) elif ext == '.mp4': audio = MP4(fn) elif ext == '.aac': audio = AAC(fn) else: logging.warning('{0} format not found!'.format(ext)) del fn_orig, fn time_length += audio.info.length print('Completed: {0} files for {1}.'.format(track_count, format_timespan(time_length)))
def create_library(self, source_path, source_type="usb"): # Todo - add regex to remove numbers from the begining of filenames to get song name (\d{1,3}|)( - |)(?P<song_Name>.+) self.library_ready = False new_library = [] for root, d_names, f_names in os.walk(str(source_path)): for fileName in f_names: audio = None foundType = [ musicType for musicType in MUSIC_TYPES if (musicType.lower() in fileName.lower()) ] if bool(foundType): song_path = str(root) + "/" + str(fileName) if True: # try: # Removed to find error if "flac" in str(foundType[0]): # add flac filter audio = FLAC(song_path) # LOG.info("Checking FLAC Tags" + str(audio)) elif "aac" in str(foundType[0]): # add flac filter: audio = AAC(song_path) # LOG.info("Checking aac Tags" + str(audio)) elif "mp3" in str(foundType[0]): # add flac filter: try: audio = EasyID3(song_path) except ID3NoHeaderError: LOG.info("No ID Tags Found... " + song_path) audio = {} # LOG.info("Checking mp3 Tags" + str(audio)) elif "m4a" in str(foundType[0]): # add flac filter: audio = MP4(song_path) # LOG.info("Checking m4a Tags" + str(audio)) if audio is not None: # An ID3 tag found if 'title' not in audio.keys(): trim_length = (len(str(foundType[0])) + 1) * -1 self.song_label = str(fileName)[:trim_length] else: self.song_label = audio['title'][0] #LOG.info("Validating title: " + self.song_label) if 'artist' not in audio.keys(): if 'Contributing artists' in audio.keys(): self.song_artist = audio[ 'Contributing artists'][0] else: self.song_artist = "" else: self.song_artist = audio['artist'][0] #LOG.info("Validating artist: " + self.song_artist) if 'album' not in audio.keys(): self.song_album = "" else: self.song_album = audio['album'][0] else: # There was no ID3 Tag found, use filename as song title trim_length = (len(str(foundType[0])) + 1) * -1 self.song_label = str(fileName)[:trim_length] self.song_artist = "" self.song_album = "" info = { "location": song_path, "label": self.song_label, "artist": self.song_artist, "album": self.song_album, "source": str(source_type) } new_library.append(info) song_count = len(new_library) if song_count == 0: self.speak_dialog('no.files', data={"source": str(source_type)}, expect_response=False) else: self.speak_dialog('scan.complete', data={ "count": str(song_count), "source": str(source_type) }, expect_response=False) wait_while_speaking() LOG.info("Added: " + str(song_count) + " to the library from the " + str(source_type) + " Device") self.library_ready = True return new_library
import os, sys, argparse, json from datetime import datetime, timedelta try: from mutagen.mp3 import MP3 from mutagen.flac import FLAC from mutagen.aac import AAC from mutagen.aiff import AIFF from mutagen.asf import ASF except ImportError as e: print("Mutagen library is not intalled...") sys.exit(1) audio_ext = { "mp3": lambda x: MP3(x).info.length, "aac": lambda x: AAC(x).info.length, "wmv": lambda x: ASF(x).info.length, "wma": lambda x: ASF(x).info.length, "asf": lambda x: ASF(x).info.length, "flac": lambda x: FLAC(x).info.length, "aiff": lambda x: AIFF(x).info.length } json_list = [] def scan_lib(path): playtime = 0 audio_files = 0 folder_audio = 0 audio_subfolders = 0 for entry in os.listdir(path): entry = os.path.join(path, entry)
def trans(tenant, multiUser, username): if request.method == 'POST': table = dynamo.Table(username) tableLog = dynamo.Table('admin-log-files') filename = request.files['files'].filename media_format = filename[-3:] multi_user_tenant = multiUser # Media_format check if media_format != "mp3": if media_format != "mp4": if media_format != "aac": if media_format != "lac": return render_template('trans.html', user=username) cur_time = str(datetime.datetime.now()) cur_period = cur_time[:7] id = username + cur_time #Upload the audio file to S3 s3.Bucket('transcribe-bucket-bzs').put_object( Key=username + '/' + filename, Body=request.files['files']) # Getting s3 file and read duration file = request.files['files'] if (media_format == 'mp3'): audio = MP3(file) if (media_format == 'mp4'): audio = MP4(file) if (media_format == 'aac'): audio = AAC(file) if (media_format == 'lac'): audio = FLAC(file) length = int(audio.info.length) print("+++ Length: " + str(length)) #Save the size of the audio file size = str( boto3.resource('s3').Bucket('transcribe-bucket-bzs').Object( username + '/' + filename).content_length) print("+++Size: " + size) #Create the log for the billing and tenant information try: tableLog.put_item( Item={ 'id': id, 'fileformat': media_format, 'size': int(size), 'period': cur_period, 'time': cur_time, 'username': username, 'length': length, 'tenant': tenant, 'multi_user_tenant': multi_user_tenant }) print("Log-files successfully uploaded!") except: print("There was an issue uploading the log-files!") try: table.put_item(Item={'file': filename, 'format': media_format}) return redirect('/transcribe/' + username + '/' + filename) except: return 'There was an issue adding your task' else: return render_template('trans.html', user=username, multiUser=multiUser, tenant=tenant)