Esempio n. 1
0
 def loadFile(self, _filePath, _tagVersion=None):
     if _tagVersion is None:
         _tagVersion = id3.ID3_V2_4
     self.tag = None
     self.info = None
     self.filePath = _filePath
     self.isCorrect = False
     self.isSave = False
     self.isNeedUpdate = False
     try:
         self.tag = id3.TagFile(
             uni.trEncode(self.filePath, fu.fileSystemEncoding),
             _tagVersion).tag
         self.info = mp3.Mp3AudioFile(
             uni.trEncode(self.filePath, fu.fileSystemEncoding)).info
     except:
         self.tag = id3.TagFile(self.filePath, _tagVersion).tag
         self.info = mp3.Mp3AudioFile(self.filePath).info
     if self.tag is None:
         self.isNeedUpdate = True
         self.isSave = True
         self.tag = id3.Tag()
         self.tag.parse(self.filePath, id3.ID3_ANY_VERSION)
     elif not self.tag.isV2():
         self.isNeedUpdate = True
         self.isSave = True
async def get_sounds():
    print(f'get_sounds: entered')
    sounds = []
    for file in os.listdir("BotFiles\Audio"):
        print(f'get_sounds: file == {file}')
        path = f'BotFiles\Audio\{file}'
        mp3_file = mp3.Mp3AudioFile(path)
        if mp3_file.tag != None:
            name = mp3_file.tag.title
            if mp3_file.tag.artist != None:
                user_names = mp3_file.tag.artist.replace(' ', '').split(',')
            else:
                user_names = []
            if mp3_file.tag.album != None:
                emoji_names = mp3_file.tag.album.replace(' ', '').split(',')
            else:
                emoji_names = []
            if mp3_file.tag.album_artist != None:
                creator_user_name = mp3_file.tag.album_artist
            else:
                creator_user_name = ''
            sounds.append(
                Sound(path, name, user_names, emoji_names, creator_user_name))
        else:
            print(f'get_sounds: bad/missing tag data')
    return sounds
Esempio n. 3
0
 def __init__(self, path, name, user_names, emoji_names, creator_user_name):
     self.path = path
     self.name = name
     self.user_names = user_names
     self.emoji_names = emoji_names
     self.creator_name = creator_user_name
     self.__mp3_file = mp3.Mp3AudioFile(path)
def openfile(index=[1]):
    global total, name  #abc

    filenames = filedialog.askopenfilenames(title="音乐播放器",
                                            filetypes=[("mp3文件", "*.mp3"),
                                                       ("WMA文件", "*.wma"),
                                                       ("WAV文件", "*.wav")])
    if filenames:
        for i in range(len(filenames)):
            media = wmp.newMedia(filenames[i])
            wmp.currentPlaylist.appendItem(media)

            print("test:" + filenames[i])
            coco = mp3.Mp3AudioFile(
                filenames[i])  # 模块更新,采用mp3.Mp3AudioFile访问目标文件
            # coco = eyed3.load(r"D:\C\Python实训\python实现本地音乐播放器\3.mp3")  # eyed3模块读取mp3信息
            total = int(coco.info.time_secs)
            minute = int(coco.info.time_secs) // 60
            sec = int(coco.info.time_secs) % 60
            length = int(coco.info.time_secs)

            name = filenames[i].split("/")

            i = index[-1]
            list_name.insert(END, str(i) + "." + name[-1])
            list_name.insert(END, " " * 6)
            if sec >= 10:
                list_name.insert(END, "0%d:%d" % (minute, sec) + "\n")
            else:
                list_name.insert(END, "0%s:0%d" % (minute, sec) + "\n")
            i = i + 1
            index.append(i)
Esempio n. 5
0
def get_atr_test():
    path = r'C:\Python\mp3\audio\Face.mp3'
    f = mp3.Mp3AudioFile(path)
    title = f.tag.title
    artist = f.tag.artist
    album = f.tag.album
    year = f.tag.getBestDate()
    genre = f.tag.genre
    bitrate = f.info.bit_rate_str
    length = f.info.time_secs
    print(year)
Esempio n. 6
0
    def music_start(self, event=None, start_seconds=0.0):
        # 设置正在播放的音乐信息
        music_path = self.current_music_path
        # 如果不存在这个路径,则退出播放
        if not music_path or not os.path.exists(music_path):
            self.__dict__["musicPath"].set("")
            return

        # 获取歌词字典,如果有的话
        self.__dict__["lyric"].set("")
        self.lyric_dict = read_lyric(
            os.path.join(
                self.music_dir_path,
                os.path.basename(self.current_music_path)[:-3] + "lrc"))

        # 设置音乐时长
        music_file = mp3.Mp3AudioFile(music_path)
        try:
            music_name_info = music_file.tag.artist + " - " + music_file.tag.title + "\n专辑:" + music_file.tag.album
        except Exception as e:
            logging.warning(e)
            music_name_info = os.path.basename(music_path)
        self.__dict__["info"].set(music_name_info)
        self.music_duration = music_file.info.time_secs
        self.__dict__["musicTime"].set(self._format_time(self.music_duration))
        # 中文路径必须编码后才可以
        if self.__dict__["volumeOnOffButton"]["text"] == "音量开":
            now_volume = self.__dict__["musicVolumeScale"].get() / 100.0
        else:
            now_volume = 0.0

        # 如果是新播放音乐或者从指定时间播放
        if self.__dict__["startButton"]["text"] == "播放" or start_seconds != 0.0:
            self.__dict__["startButton"]["image"] = self.pause_img
            self.__dict__["startButton"]["text"] = "暂停"
            if start_seconds != 0.0:
                self.adjust_time_count_stop()
            else:
                self.play_time_count_stop()
            if self.player:
                self.player.stop_state = True
                self.player = None
                time.sleep(1)
            self.player = Player(
                self.__dict__["musicPath"].get().encode('utf-8'), now_volume,
                start_seconds, self)
            self.player.start()
            self.play_time_count_start(start_seconds=start_seconds)
            self.count_music_play_times(music_path)
        else:
            self.music_pause_restore()
Esempio n. 7
0
def musicFilter(music):
    ret = []
    names = []
    for i in music:
        p = mp3.Mp3AudioFile(i)
        if p is not None:
            try:
                if p.info.time_secs > 50:
                    if p.tag.title not in names or p.tag.title is None:
                        names.append(p.tag.title if p.tag.title is not None else None)
                        ret.append(singleMusic(p.info.time_secs, i,p.tag.title,p.tag.artist,p.tag.album))
            except AttributeError or TypeError:
                continue
    for i in ret:
        i.generalInfo()
    return ret
Esempio n. 8
0
def edit_tags(tags_list):
    for i in tags_list:
        if i.get('filepath') and i.get('artist'):
            print(i.get('filepath'))
            f = mp3.Mp3AudioFile(i.get('filepath'))
            if i.get("title"):
                f.tag.artist = i.get("title")
            if i.get("artist"):
                print(i.get("artist"))
                f.tag.artist = i.get("artist")
            if i.get("album"):
                f.tag.album = i.get("album")
            if i.get("genre"):
                f.tag.genre.name = i.get("genre")
            # todo тут запись года

            f.tag.save()
Esempio n. 9
0
def get_tags(folder):
    if os.path.exists(folder):
        files_paths = []
        for path, subdirs, files in os.walk(folder):
            files_paths.extend([
                os.path.join(path, name) for name in files
                if name[-4:] == ".mp3"
            ])
            #todo убрать дубликаты
        print(files_paths)
        tags_list = []
        for file in files_paths:
            f = mp3.Mp3AudioFile(file)
            if f.tag:
                # если нет жанра
                if f.tag.genre:
                    genr = f.tag.genre.name
                else:
                    genr = None
                # todo сделать обработку бардака с кодировками
                tags_list.append({
                    "filepath": file,
                    "title": f.tag.title,
                    "artist": f.tag.artist,
                    "album": f.tag.album,
                    "year": str(f.tag.getBestDate()),
                    "genre": genr,
                    "bitrate": f.info.bit_rate_str,
                    "length": f.info.time_secs,
                })
            else:
                tags_list.append({
                    "filepath": file,
                    "title": None,
                    "artist": None,
                    "album": None,
                    "year": None,
                    "genre": None,
                    "bitrate": None,
                    "length": None,
                })

        return tags_list

    else:
        return "Не правильно указан каталог!"
Esempio n. 10
0
async def get_sound(path):
    print(f'get_sound: entered')
    sound = None
    if not os.path.exists(path):
        print(f'get_sound: path {path} does not exist')
        return
    mp3_file = mp3.Mp3AudioFile(path)
    if mp3_file.tag != None:
        name = mp3_file.tag.title
        if mp3_file.tag.artist != None:
            user_names = mp3_file.tag.artist.replace(' ', '').split(',')
        else:
            user_names = []
        if mp3_file.tag.album != None:
            emoji_names = mp3_file.tag.album.replace(' ', '').split(',')
        else:
            emoji_names = None
        sound = Sound(path, name, user_names, emoji_names)
    else:
        print(f'get_sound: bad/missing tag data')
    return sound
Esempio n. 11
0
def download_audio(id_title):
    id, title = id_title
    api_url = 'https://tw.streetvoice.com/api/v3/songs/{}/?only_fields=file'

    try:
        test = urllib.FancyURLopener()
        response = urllib.urlopen(api_url.format(id))
        data = json.loads(response.read())

        audio_url = data['file']

        save_name = path.join(SAVE_FOLDER, '%s.mp3' % title)
        test.retrieve(audio_url, save_name)

        f = mp3.Mp3AudioFile(save_name)
        print('Frequency: %10d  bit rate: %10d Song: %50s \n' %
              (f.info.sample_freq, f.info.bit_rate[1], title))

    except Exception as e:
        print(title)
        raise e
def main():
    args = get_script_arguments()
    if not os.path.exists(args.output_dir):
        os.makedirs(args.output_dir)
    elif args.force:
        shutil.rmtree(args.output_dir)
        os.makedirs(args.output_dir)
    else:
        print(f'{args.output_dir} already exists. Delete it first.')
        exit(1)

    for input_filename in glob(args.input_dir + '/**/*.mp3', recursive=True):
        music_name = os.path.basename(input_filename)
        output_filename = os.path.join(args.output_dir, music_name)
        # just to avoid this warning: Invalid date: 20091201, we add version.
        f = mp3.Mp3AudioFile(input_filename, version=ID3_V1_0)
        if args.min_minutes * 60 < f.info.time_secs < args.max_minutes * 60:
            print(f'KEEP {input_filename}.')
            if not args.dry_run:
                shutil.copy2(input_filename, output_filename)
        else:
            print(f'DELETE {input_filename}.')

    print('Completed.')
Esempio n. 13
0
        writev(clip)
    else:
        writev(clip, file_name)

elif func == "2":
    print("请输入需要剪切的音频的路径:")
    file = input()
    clip = opena(file)
    print("请输入剪切起始时间(小时:分钟:秒):")
    start = input()
    print("请输入剪切终止时间(小时:分钟:秒):")
    end = input()
    clip = cut(clip, start, end)
    print("请输入输出文件名(默认为 output.mp3)")
    file_name = input()
    f = mp3.Mp3AudioFile(file)
    bit_rate = f.info.bit_rate[1] * 1000
    if file_name == "":
        writea(clip, bit_rate)
    else:
        writea(clip, file_name, bit_rate)

elif func == "3":
    print("请输入生成gif的视频的路径:")
    file = input()
    clip = openv(file)
    print("请输入生成起始时间(小时:分钟:秒):")
    start = input()
    print("请输入生成终止时间(小时:分钟:秒):")
    end = input()
    clip = cut(clip, start, end)
Esempio n. 14
0
 async def set_title(title):
     __mp3_file = mp3.Mp3AudioFile()
     __mp3_file.tag._setTitle(title)
Esempio n. 15
0
#!/usr/bin/env python
import argparse
from eyed3 import mp3

try:
    from colored import fg, attr
except ImportError:
    fg = lambda *_: ''
    attr = fg

parser = argparse.ArgumentParser(
    description='Validate an MP3 file for use in an Alexa SSML <audio> tag.')
parser.add_argument('file', help='MP3 file to check')
args = parser.parse_args()

info = mp3.Mp3AudioFile(args.file).info
valid = True


def test_true(statement, description):
    global valid
    if statement == True:
        print(u'{0}\u2713 {description[0]} is {description[1]}{1}'.format(
            fg('green'), attr('reset'), description=description))
    else:
        print(
            u'{0}\u2715 {description[0]} should be {description[1]} (it\'s {description[2]}){1}'
            .format(fg('red'), attr('reset'), description=description))
        valid = False

Esempio n. 16
0
import os
import mp3Main
#from mp3Main import set_rootdir
import pathlib
import errno

rootdir = mp3Main.set_rootdir()

#artist folder creation and garbage collection.

for root, dirs, files in os.walk(rootdir):
    for name in files:
        try:
            audioFile = eyed3.load(os.path.join(root, name))
            songArtist = audioFile.tag.artist
            tag = mp3.Mp3AudioFile(os.path.join(root, name))
            x = (tag.info.bit_rate)
            bitRate = str(x[1])

            # search string for  numbers, /xxx/ if it comes with 1 then don't proceed with code
            #if bitRate.__len__() <= 2:
            #    bitRate = bitRate.zfill(3)

            source = os.path.join(root, name)
            dest = os.path.join(rootdir, songArtist, bitRate, name)

            pathlib.Path(rootdir, bitRate).mkdir(parents=True, exist_ok=True)
            print(dest)
            os.rename(source, dest)
        except:
            #creating the garbage root outside of the music directory stops it from being scanned by the rest of the program
Esempio n. 17
0
import re
import glob
from eyed3 import mp3
from pprint import pprint

# use python 2.7
# command: youtube-dl --download-archive downloaded.txt --no-post-overwrites -ciwx --extract-audio --audio-format mp3 -o "%(autonumber)s %(title)s.%(ext)s" [url]
# navigate to OUTPUT TEMPLATE section of the man page for youtube-dl for all templates
os.chdir("/Users/Woz4tetra/Downloads/playlist")
audiofiles = glob.glob("*.mp3") + glob.glob("*.m4a") + glob.glob("*.flac") 

dry_run = False

for file_name in audiofiles:
    match = re.match(r"(\d*) ([\s\S]*) - [\s\S]*\.mp3", file_name)
    if match is not None:
        track_num = int(match.group(1))
        new_name = match.group(2)
        
        mp3_file = mp3.Mp3AudioFile(file_name)
        mp3_file.initTag()
        mp3_file.tag.track_num = (track_num, len(audiofiles))
        mp3_file.tag.album = u"Super Mario Odyssey Soundtrack"
        
        if not dry_run:
            mp3_file.tag.save()
            
            mp3_file.rename(unicode(new_name, 'utf-8'))
        print("%s ---> %s" % (file_name, new_name))
            
Esempio n. 18
0
from eyed3 import mp3
import os
path = os.getcwd()
for music_file in os.listdir(path) :
    cursor = "{}/{}".format(path, music_file)
    if music_file[-4:] == ".mp3" : 
        trackinfo = mp3.Mp3AudioFile(cursor)
        dir_album = "{}/{} - {}".format(path, trackinfo.tag.artist, trackinfo.tag.album)
        # ensure album dir exists
        if not os.path.isdir(dir_album) :
            os.mkdir(dir_album)
        os.rename(path+"/"+music_file, dir_album+"/"+music_file)
Esempio n. 19
0
# pip install eyeD3

import eyed3
from eyed3 import mp3
f = mp3.Mp3AudioFile('2-297a587f40fdc0064c44f2e5247d7bf7.mp3')

# Now: 
# >>> f.info.sample_freq
# 24000
# >>> f.info.bit_rate
# (False, 64)
# >>> f.info.mode
# 'Mono'