Example #1
0
 def test_id3_indicates_mp3_not_tta(self):
     header = b"ID3 the rest of this is garbage"
     fileobj = cBytesIO(header)
     filename = "not-identifiable.ext"
     self.failUnless(TrueAudio.score(filename, fileobj, header) <
                     MP3.score(filename, fileobj, header))
Example #2
0
def loadFile(location):
    audioFile = MP3(location)
    print("Opened file {0}.".format(location))
    return audioFile
Example #3
0
def createMP3Track(filePath, convert, fileTypeId, coverPath):
    track = LocalTrack()

    # --- FILE INFORMATION ---
    audioFile = MP3(filePath)
    track.location = filePath
    track.size = os.path.getsize(filePath)
    track.bitRate = audioFile.info.bitrate
    track.duration = audioFile.info.length
    track.sampleRate = audioFile.info.sample_rate
    if audioFile.info.bitrate_mode == BitrateMode.UNKNOWN:
        track.bitRateMode = 0
    elif audioFile.info.bitrate_mode == BitrateMode.CBR:
        track.bitRateMode = 1
    elif audioFile.info.bitrate_mode == BitrateMode.VBR:
        track.bitRateMode = 2
    else:
        track.bitRateMode = 3
    track.fileType = fileTypeId.id

    # Generating moodbar hash
    path = track.location.encode("ascii", "ignore")
    md5 = hashlib.md5(path).hexdigest()
    track.moodbar = "../static/mood/" + md5 + ".mood"

    # Check if the file has a tag header
    try:
        audioTag = ID3(filePath)
    except ID3NoHeaderError:
        audioTag = ID3()
    # --- FILE TAG ---
    if convert:
        audioTag.update_to_v24()
        audioTag.save()

    # --- COVER ---
    if 'APIC:' in audioTag:
        front = audioTag['APIC:'].data
        # Creating md5 hash for the cover
        md5Name = hashlib.md5()
        md5Name.update(front)
        # Check if the cover already exists and save it
        if not os.path.isfile(coverPath + md5Name.hexdigest() + ".jpg"):
            with open(coverPath + md5Name.hexdigest() + ".jpg", 'wb') as img:
                img.write(front)
        track.coverLocation = md5Name.hexdigest() + ".jpg"
    if 'TIT2' in audioTag:
        if not audioTag['TIT2'].text[0] == "":
            track.title = strip_tags(audioTag['TIT2'].text[0]).rstrip()

    if 'TDRC' in audioTag:
        if not audioTag['TDRC'].text[0].get_text() == "":
            track.year = strip_tags(audioTag['TDRC'].text[0].get_text()[:4]).rstrip()  # Date of Recording

    if 'TRCK' in audioTag:
        if not audioTag['TRCK'].text[0] == "":
            if "/" in audioTag['TRCK'].text[0]:  # Contains info about the album number of track
                tags = strip_tags(audioTag['TRCK'].text[0]).rstrip().split('/')
                track.number = tags[0]
                track.totalTrack = tags[1]
            else:
                track.number = strip_tags(audioTag['TRCK'].text[0]).rstrip()

    if 'TCOM' in audioTag:
        if not audioTag['TCOM'].text[0] == "":
            track.composer = strip_tags(audioTag['TCOM'].text[0]).rstrip()

    if 'TOPE' in audioTag:
        if not audioTag['TOPE'].text[0] == "":
            track.performer = strip_tags(audioTag['TOPE'].text[0]).rstrip()

    if 'TBPM' in audioTag:
        if not audioTag['TBPM'].text[0] == "":
            track.bpm = math.floor(float(strip_tags(audioTag['TBPM'].text[0]).rstrip()))

    if 'COMM' in audioTag:
        if not audioTag['COMM'].text[0] == "":
            track.comment = strip_tags(audioTag['COMM'].text[0]).rstrip()

    if 'USLT' in audioTag:
        if not audioTag['USLT'].text[0] == "":
            track.lyrics = strip_tags(audioTag['USLT'].text[0])

    if len(audioTag.getall('TXXX')) != 0:
        for txxx in audioTag.getall('TXXX'):
            if txxx.desc == 'TOTALDISCS':
                totalDisc = strip_tags(txxx.text[0]).rstrip()

    # --- Adding genre to structure ---
    if 'TCON' in audioTag:
        genreName = strip_tags(audioTag['TCON'].text[0]).rstrip()
        track.genre = genreName

    # --- Adding artist to structure ---
    if 'TPE1' in audioTag:  # Check if artist exists
        artists = strip_tags(audioTag['TPE1'].text[0]).split(",")
        for artistName in artists:
            artistName = artistName.lstrip().rstrip()  # Remove useless spaces at the beginning
            track.artist.append(artistName)

    # --- Adding album to structure ---
    if 'TALB' in audioTag:
        albumTitle = strip_tags(audioTag['TALB'].text[0]).rstrip()
        track.album = albumTitle.replace('\n', '')

    return track
Example #4
0
from datetime import date
from pathlib import Path

import pygame
from mutagen.mp3 import MP3

voice_dir = Path.cwd() / "voice"
call_path = voice_dir / "se" / "chakusin.mp3"
config_dir = Path.cwd() / "config"

today = date.today()
config_file = config_dir / f"{today.year}-{str(today.month).zfill(2)}.json"
with open(str(config_file), "r", encoding="utf-8") as f:
    himekuri_voice_path_dict = json.load(f)
himekuri_voice_path = himekuri_voice_path_dict[str(today.day).zfill(2)]

pygame.mixer.init()
pygame.mixer.music.load(str(call_path))
pygame.mixer.music.set_volume(0.5)
call_len = MP3(str(call_path)).info.length
pygame.mixer.music.play(10)
enter = input("enter")
pygame.mixer.music.stop()

pygame.mixer.init()
pygame.mixer.music.load(str(himekuri_voice_path))
pygame.mixer.music.set_volume(1.0)
himekuri_len = MP3(str(himekuri_voice_path)).info.length
pygame.mixer.music.play(1)
time.sleep(himekuri_len + 0.25)
pygame.mixer.music.stop()
Example #5
0
 def get_song_length(self,song_name):
     self.song_path=self.my_model.get_song_path(song_name)
     self.audio_tag=MP3(self.song_path)
     song_length=self.audio_tag.info.length
     return song_length
Example #6
0
async def play(ctx, *url: str):
    Timer = time.time()
    await Tired(ctx=ctx)
    SongListData = []
    JoinedURL = ' '.join(url)
    voice = get(bot.voice_clients, guild=ctx.guild)

    song_there = os.path.isfile("Song.mp3")
    SongList = []
    Int = 0

    try:
        for i in os.listdir("./"):
            if i.endswith(".mp3"):
                os.remove(i)
                SongList.clear()
                Int = 0
    except PermissionError:
        print("Song being used")
        await ctx.send(
            "Music is currently playing. Please wait for it to finish")
        return

    print("Getting ready to dowload the song")
    await ctx.send(
        "Now downloading your selected song. Please be patient it might take a while(Especially with spotify songs)"
    )

    ydl_opts = {
        "format":
        "bestaudio/best",
        "quite":
        True,
        "postprocessors": [{
            "key": "FFmpegExtractAudio",
            "preferredcodec": "mp3",
            "preferredquality": "192",
        }],
    }

    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            print("Dowload object made, now dowloading song")
            ydl.download([JoinedURL])
    except Exception:
        try:
            Temp = JoinedURL.replace(" ", "_")
            C_Path = os.path.dirname(os.path.realpath("Queue"))
            system(f"spotdl ${Temp}")
        except Exception:
            print("User didnt give an actual url")
            await ctx.send(
                f"Give me an actuall Youtube or Spotify url please and not '**{JoinedURL}**'. You can also specify a song name(EX: ``Linda p BFG Division``) <@{ctx.author.id}>"
            )

    print(f"Song download took {time.time() - Timer}")

    for i in os.listdir("./"):
        if i.endswith(".mp3"):
            SongListData.append(i)
            SongList.append(f"Song{Int}.mp3")
            print(f"File {i} found, now renaming")
            os.rename(i, f"Song{Int}.mp3")
            Int = Int + 1

    async def p_song(itter):
        voice.play(discord.FFmpegPCMAudio(itter),
                   after=lambda e: print("Now playing next song"))
        voice.source = discord.PCMVolumeTransformer(voice.source)
        voice.source.volume = 0.10
        #T = str(SongListData).replace(".mp3","").replace("-"," ").replace(",","\n").replace("[","").replace("]","")
        Emoji = discord.utils.get(bot.emojis, name="xar")
        Embed = discord.Embed(
            title="Now Playing",
            description=f"{str(Emoji)} **{JoinedURL}** {str(Emoji)}",
            color=discord.Color.green())
        await ctx.send(embed=Embed)

    for i in SongList:
        await p_song(i)
        print(f"Song length is {MP3(i).info.length}")
        await asyncio.sleep(MP3(i).info.length)

    SongListData.clear()
Example #7
0
txt_height = txt.count('\n')
txt = 10*"\n" +txt + 10*"\n"

# Fix problems with ASCII code
printable = set(string.printable)
audio_txt = filter(lambda x: x in printable, origin_txt)

# Create audio and get audio duration
audiofn = "audio.mp3"
if len(AUDIO_FILE) == 0:
    myobj = gTTS(text=audio_txt, lang=language, slow=False) 
    myobj.save(audiofn)
else:
    audiofn = AUDIO_FILE
audio = AudioFileClip(audiofn)
duration = MP3(audiofn).info.length

# Create the Text clip
text = TextClip(txt,color=FONT_COLOR, align='West',fontsize=26,
                    font=FONT_FAMILY, method='label')

#title_txt = TextClip(TITLE_TEXT,color=FONT_COLOR, align='West',fontsize=26,
                    #font=FONT_FAMILY, method='label')

if len(BACKGROUND_IMAGE) > 0:
    bg = ImageClip(BACKGROUND_IMAGE)

# Scroll the text at the right speed
line_height = 30
txt_speed = float(line_height) * float(txt_height) / float(duration)
Example #8
0
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.jpeg"):
		os.remove("/tmp/.emcAudioTag.jpeg")
	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))
Example #9
0
def MP3PLAYING():  #Main interface which initiates the MP3 player
    global seek
    global oc2
    global listofsongs
    global listofsongs2
    global songlist
    global songname 
    global len1
    global time1
    songname=Label(root5,textvariable=m,width=90,bg="#220047",fg="#CE9141",font=("roboto",13))
    songname.place(x=-120,y=450)
        
    pygame.mixer.init()
    songlist=Listbox(root5,selectbackground="#CE9141",height=14,width=60,relief=GROOVE,bd=3,bg="#220047",fg="#CE9141",font=("fixedsys",10))
    songlist.place(x=20,y=205)
  
    a=StringVar()
    a.set("Default")
    
    oc=StringVar(root5)
    oc.set("Select")
    
    
    listofsongs2.reverse()
    for h in listofsongs2:
        songlist.insert(0,h)
    listofsongs2.reverse()
    
    #currentsong=Label(root5,text="Current Song:",font=("georgia",15),bg="#220047",fg="#CE9141")
    #currentsong.place(x=230,y=500)
    
    orderofsongs=Label(root5,text="Your Playlist",font=("georgia",15),bg="#220047",fg="#CE9141")
    orderofsongs.place(x=40,y=170)
    
    startbutton=Button(root5,text="Start",bg="#CE9141",relief=RAISED,fg="#220047",bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10))
    startbutton.place(x=400,y=480)
    
    playnext=Button(root5,text=">>>",bg="#CE9141",relief=RAISED,fg="#220047",bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10))
    playnext.place(x=355,y=480)
    
    
    playbefore=Button(root5,text="<<<",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10))
    playbefore.place(x=190,y=480)
    
    stop=Button(root5,text="Stop",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10))
    stop.place(x=137,y=480)
    
    pause=Button(root5,text="Pause",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10))
    pause.place(x=237,y=480)
     
    play=Button(root5,text="Play",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10))
    play.place(x=300,y=480)

    volume1=Label(root5,text="Volume",font=("georgia",11),fg="#CE9141",bg="#220047")
    volume1.place(x=533,y=190)
    
    selection=MP3(listofsongs[0])
    len1=selection.info.length
    len1//=1
 
    seek=Scale(root5,from_=0,to=len1,orient=HORIZONTAL,length=400,cursor="cross",bd=1,bg="#CE9141",fg="#220047",activebackground="#220047",command=seek1)
    seek.place(x=100,y=530)
    
    oc1=StringVar(root5)
    oc1.set("Welcome"+ " "+ user11)
    
    options=["Home","Back","Close"]
    dropdown=OptionMenu(root5,oc1,*options,command=choice1)
    dropdown.configure(font=("georgia",15),fg="#220047",bg="#CE9141",activebackground="#CE9141",activeforeground="#220047")
    dropdown.place(x=200,y=110)
    
    oc2=StringVar(root5)
    oc2.set("Options")
    
    options1=["Shuffle[]","Random[?]","Delete[-]","Add[+]"]
    dropdown1=OptionMenu(root5,oc2,*options1,command=choice2)
    dropdown1.configure(text="Options",font=("georgia",10),fg="#220047",bg="#CE9141",activebackground="#220047",activeforeground="#CE9141")
    dropdown1.place(x=500,y=50)
    
    volume2=Scale(root5,from_=100,to=0,orient=VERTICAL,length=210,cursor="cross",bd=1,bg="#CE9141",fg="#220047",activebackground="#220047",command=volume)
    volume2.set(100)
    volume2.place(x=540,y=215)
    pygame.mixer.music.set_volume(100)
    
    if conditionalval==2:
        saveplaylist=Button(root5,text="Save",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10))
        saveplaylist.place(x=40,y=560)
        saveplaylist.bind("<Button>",createplay)
    elif conditionalval==3:
        orderofsongs.place_forget()
        defer="Your Playlist :"+" "+appendlist
        orderofsongs=Label(root5,text=defer,font=("georgia",15),bg="#220047",fg="#CE9141")
        orderofsongs.place(x=40,y=170)
        
    else:
        print("okay")

    
    """time1=IntVar()
    time1.set(0)

    timer1= Label(root5, textvar= time1,font=("georgia",8),fg="#220047",bg="#CE9141")
    timer1.place(x= 250, y= 550)"""
    
    pause.bind("<Button-1>",pausesong)
    play.bind("<Button-1>",unpause)
    startbutton.bind("<Button-1>",playmusic)
    playnext.bind("<Button-1>",nextsong)
    playbefore.bind("<Button-1>",previous)
    stop.bind("<Button-1>",stopmusic)

    pygame.mixer.music.load(listofsongs[0])
    pygame.mixer.music.play()


    updatename()
    """timer()
Example #10
0
rtmp = var_set.rtmp
live_code = var_set.live_code

def convert_time(n):
    s = n%60
    m = int(n/60)
    return '00:'+"%02d"%m+':'+"%02d"%s

while True:
    try:
        files = os.listdir(path+'/downloads')
        files.sort()
        count=0
        for f in files:
            if((f.find('.mp3') != -1) and (f.find('.download') == -1)):
                audio = MP3(path+'/downloads/'+f)
                seconds=audio.info.length   #获取时长
                print('mp3 long:'+convert_time(seconds))
                if(seconds > 600):
                    print('too long,delete')
                else:
                    pic_files = os.listdir(path+'/default_pic')
                    pic_files.sort()
                    pic_ran = random.randint(0,len(pic_files)-1)
                    print('ffmpeg -re -s 1280x720 -loop 1 -r 3 -t '+str(int(seconds))+' -f image2 -i "'+path+'/default_pic/'+pic_files[pic_ran]+'" -i "'+path+'/downloads/'+f+'" -vf ass="'+path+"/downloads/"+f.replace(".mp3",'')+'.ass'+'" -pix_fmt yuv420p -crf 24 -preset ultrafast -maxrate 1000k -acodec aac -b:a 192k -c:v h264_omx -f flv "'+rtmp+live_code+'"')
                    os.system('ffmpeg -re -s 1280x720 -loop 1 -r 3 -t '+str(int(seconds))+' -f image2 -i "'+path+'/default_pic/'+pic_files[pic_ran]+'" -i "'+path+'/downloads/'+f+'" -vf ass="'+path+"/downloads/"+f.replace(".mp3",'')+'.ass'+'" -pix_fmt yuv420p -crf 24 -preset ultrafast -maxrate 1000k -acodec aac -b:a 192k -c:v h264_omx -f flv "'+rtmp+live_code+'"')
                try:
                    os.remove(path+'/downloads/'+f)
                    os.remove(path+'/downloads/'+f.replace(".mp3",'')+'.ass')
                    os.remove(path+'/downloads/'+f.replace(".mp3",'')+'.info')
                except:
from mutagen.mp3 import MP3
import os
from shutil import move

folder = "E:\WhatsApp Audio"
for file in os.listdir(folder):
    audio = MP3(folder + '\\' + file)
    print file
    print "------------------------"
    print audio.pprint()
    print "------------------------"
    print
    OldPath = folder + '\\' + file
    try:
        Author = str(audio.tags["TPE1"]).replace("'", "")
        AuthorLen = len(Author)
        Author = Author[0:AuthorLen]
        Title = str(audio.tags["TIT2"]).replace("'", "")
        TitleLen = len(Title)
        Title = Title[0:TitleLen]
        NewPath = unicode(folder + '\\' + Author + " - " + Title + ".mp3",
                          "utf-8")
        try:
            move(OldPath, NewPath)
        except:
            print "not Good"
    except:
        print "the file: " + file + " has not Metadata!"
        print
        continue
Example #12
0
import os
from mutagen.mp3 import MP3
from functions import ceil
# Format information: 
# 0: nothing
# 1: single hit
# 2: hold

resolution = 50 # ms
songLength = MP3('audio.mp3').info.length*1000 # ms

original_file = open("original.osu", "r")
original_lines = original_file.readlines()

# Remove line returns from original file
for i in range(0, len(original_lines)):
    original_lines[i] = original_lines[i].rstrip('\r\n')

original_hit_objects = original_lines[original_lines.index("[HitObjects]")+1:len(original_lines)]

poses = []
for i in range(0, len(original_hit_objects)):
    try:
        output = str(original_hit_objects[i][:-1]).split(',')
        
        # Numberize normal inputs
        for j in range(0, len(output)-1):
            output[j] = int(output[j])

        # Numberize extra inputs
        last_index = len(output)-1
Example #13
0
    def __init__(self,
                 filename=None,
                 mediatype=gpod.ITDB_MEDIATYPE_AUDIO,
                 proxied_track=None,
                 podcast=False,
                 ownerdb=None):
        """Create a Track object.

        If from_file or filename is set, the file specified will be
        used to create the track.

        The mediatype parameter sets the mediatype for the track.  It
        defaults to audio, unless 'podcast' is True, in which case it
        is set to podcast.  See gpod.ITDB_MEDIATYPE_* for other valid
        mediatypes.

        If proxied_track is set, it is expected to be an Itdb_Track
        object.

        If podcast is True then the track will be setup as a Podcast,
        unless proxied_track is set.

        """

        if filename:
            self._track = gpod.itdb_track_new()
            self['userdata'] = {
                'transferred': 0,
                'hostname': socket.gethostname(),
                'charset': defaultencoding
            }
            self['userdata']['pc_mtime'] = os.stat(filename).st_mtime
            self._set_userdata_utf8('filename', filename)
            possible_image = os.path.join(
                os.path.split(filename)[0], 'folder.jpg')
            if os.path.exists(possible_image):
                self.set_coverart_from_file(possible_image)
            try:
                audiofile = MP3(self._userdata_into_default_locale('filename'))
            except Exception, e:
                raise TrackException(str(e))
            for tag, attrib in (('TPE1', 'artist'), ('TIT2', 'title'),
                                ('TBPM', 'BPM'), ('TCON', 'genre'),
                                ('TALB', 'album'), ('TPOS', ('cd_nr', 'cds')),
                                ('TRCK', ('track_nr', 'tracks'))):
                try:
                    value = audiofile[tag]
                    if isinstance(value, mutagen.id3.NumericPartTextFrame):
                        parts = map(int, value.text[0].split("/"))
                        if len(parts) == 2:
                            self[attrib[0]], self[attrib[1]] = parts
                        elif len(parts) == 1:
                            self[attrib[0]] = parts[0]
                    elif isinstance(value, mutagen.id3.TextFrame):
                        self[attrib] = value.text[0].encode('UTF-8', 'replace')
                except KeyError:
                    pass
            if self['title'] is None:
                self['title'] = os.path.splitext(os.path.split(
                    filename)[1])[0].decode(defaultencoding).encode('UTF-8')
            self['tracklen'] = int(audiofile.info.length * 1000)
            self.set_podcast(podcast)
Example #14
0
import os
from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3
import eyed3

for root, dirs, files in os.walk("music/"):
    for name in files:
        try:
            fullpath = os.path.join(root, name)
            audio = MP3(fullpath, ID3=EasyID3)
            audio.pprint()
            #trackInfo = eyed3.Mp3AudioFile(fullpath)
            #tag = trackInfo.getTag()
            #tag.link(path)
            print(audio)
        except Exception as e:
            print(e)
Example #15
0
def read_tags(path, genre_separator):
    from mutagen.id3 import ID3
    from mutagen.mp3 import MP3
    from mutagen.mp4 import MP4

    try:
        audio = MP4(path)
        tags = {
            'title': str(audio['\xa9nam'][0]),
            'artist': str(audio['\xa9ART'][0]),
            'album': str(audio['\xa9alb'][0]),
            'duration': int(audio.info.length),
            'albumartist': None,
            'genres': None
        }
        if 'aART' in audio:
            tags['albumartist'] = str(audio['aART'][0])
        if '\xa9gen' in audio:
            tags['genres'] = []
            for g in audio['\xa9gen']:
                tags['genres'].append(str(g))
        #_LOGGER.debug('MP4 File: %s Meta: %s' % (path, json.dumps(tags)))
        return tags
    except:
        pass

    try:
        audio = MP3(path)
        tags = {
            'title': str(audio['TIT2']),
            'artist': str(audio['TPE1']),
            'album': str(audio['TALB']),
            'duration': int(audio.info.length),
            'albumartist': None,
            'genres': None
        }
        if 'TPE2' in audio:
            tags['albumartist'] = str(audio['TPE2'])
        if 'TCON' in audio:
            tags['genres'] = str(audio['TCON']).split(genre_separator)
        #_LOGGER.debug('MP3 File: %s Meta: %s' % (path, json.dumps(tags)))
        return tags
    except Exception as e:
        #print("EX:%s" % str(e))
        pass

    try:
        audio = ID3(path)
        tags = {
            'title': str(audio['TIT2']),
            'artist': str(audio['TPE1']),
            'album': str(audio['TALB']),
            'duration': 0,
            'albumartist': None,
            'genres': None
        }
        if 'TPE2' in audio:
            tags['albumartist'] = str(audio['TPE2'])
        if 'TCON' in audio:
            tags['genres'] = str(audio['TCON']).split(genre_separator)
        #_LOGGER.debug('ID3 File: %s Meta: %s' % (path, json.dumps(tags)))
        return tags
    except:
        pass

    audio = get_ogg_or_flac(path)
    if audio:
        tags = {
            'title': str(audio['TITLE'][0]),
            'artist': str(audio['ARTIST'][0]),
            'album': str(audio['ALBUM'][0]),
            'duration': int(audio.info.length),
            'albumartist': None,
            'genres': None
        }
        if 'ALBUMARTIST' in audio:
            tags['albumartist'] = str(audio['ALBUMARTIST'][0])
        if 'GENRE' in audio:
            tags['genres'] = []
            for g in audio['GENRE']:
                tags['genres'].append(str(g))
        #_LOGGER.debug('OGG File: %s Meta: %s' % (path, json.dumps(tags)))
        return tags

    _LOGGER.debug('File:%s Meta:NONE' % path)
    return None
Example #16
0
# Get Sample Rate: Specifically MP3 file

from mutagen.mp3 import MP3

audio_info = MP3('Rival_Consoles_-_Persona_-_9_Untravel.mp3').info

print(audio_info.sample_rate)
Example #17
0
 def duration(self) -> int:
     return int(MP3(self.path).info.length)
        #Look for a id match
        if (playlist['id'] == entry['id']):
            #Loop through the tracks in each playlist
            for track in entry['tracks']:
                #Look for the name of each song
                for song in library:
                    #If the id's match
                    if (song['id'] == track['trackId']):
                        #Loop through the directory structure
                        for currDir, subDirectories, files in os.walk(rootDir):
                            #Loop through the files
                            for file in files:
                                #If the file is a mp3
                                if (file.endswith('.mp3')):
                                    #Load the mp3
                                    mp3File = MP3(os.path.join(currDir, file))

                                    #If the tag data matches
                                    if ((song['artist'] == mp3File['TPE1']) and
                                        (song['title'] == mp3File['TIT2'])):
                                        #Print the playlist, artist and title info
                                        print(playlist['name'] + ": " +
                                              song['artist'] + " - " +
                                              song['title'] + " Path: " +
                                              os.path.join(currDir, file))

                                        #Write to the file
                                        m3uFile.write(
                                            os.path.join(currDir, file) + '\n')

    #Close the file
Example #19
0
 songnameextension = songname[-4:]
 if songnameextension == ".mp3":  #detecting if the full file name has been inputted..
     helloyall = "hi!"
 else:
     songname = songname + ".mp3"
     #print("Fixed!")
     #print(songname)
 os.system(f"title 🐝 Bumblebee MP3 - Playing {songname} 🐝")
 repeatcount = int(
     input(
         "                How many times do you want your song repeated?\n                >"
     ))
 os.system(
     f"title 🐝 Bumblebee MP3 - Playing {songname} {str(repeatcount)} Times🐝"
 )
 song = MP3(songname)
 songLength = song.info.length
 looptime = int(songLength) + 1
 titlecount = repeatcount
 os.system('cls')
 print(logo)
 for keyroneiaahhh in range(repeatcount):
     mixer.init()
     mixer.music.load(songname)
     mixer.music.play()
     titlecount = titlecount - 1
     currentDT = datetime.datetime.now()
     hour = str(currentDT.hour)
     minute = str(currentDT.minute)
     second = str(currentDT.second)
     print(
Example #20
0
from mutagen.mp3 import MP3

parser = argparse.ArgumentParser()
parser.add_argument('path', nargs='?', default='.')
parser.add_argument('--no-sort', '-n', action='store_true')
args = parser.parse_args()

mp3s = []

for directory, _, files in os.walk(args.path):
    for basename in sorted(files):
        filename = os.path.join(directory, basename)
        if basename.lower().endswith('.mp3'):
            try:
                audio = MP3(filename)
                # print(basename, audio.info.length)
                mp3s.append(
                    (datetime.timedelta(seconds=int(audio.info.length)),
                     filename))
            except:
                print('Processing', filename, 'failed!')

if not args.no_sort:
    mp3s.sort()

total = datetime.timedelta()

for i, (duration, filename) in enumerate(mp3s):
    print(i + 1, duration, filename)
    total += duration
Example #21
0
import os
import mutagen
from mutagen.mp3 import MP3

path = os.getcwd()
total_time = 0
files = os.listdir(path)
#print files
for filename in files:
    if filename.endswith('.mp3'):
        #print path+filename
        audio = MP3(path + '/' + filename)
        total_time += audio.info.length / 3600
        print audio.info.length / 3600
print 'Total time is %0.2f' % total_time, 'hours'
Example #22
0
def  play_time():
	      #   Check   for  double  timing
	      if  stopped:
	      	        return
	      #  Grab  Current   song   Elapsed  Time
	      current_time  =   pygame.mixer.music.get_pos()  /  1000

	      #  throw   up  temp  label   to   get   data
	      #slider_label.config(text=f'Slider:  {int(my_slider.get())}   and   Song  Pos:   {int(current_time)}')
	      #  convert   to  time   format
	      converted_current_time  =   time.strftime('%M:%S',   time.gmtime(current_time))

	      #  Get   Currently   Playing   Song
	      #current_song  =    song_box.curselection()
	      #Grab   song   title   from  playlist
	      song   =   song_box.get(ACTIVE)
	      #   add   directory   structure  and   mp3   to   song   title
	      song   =   f'{song}.mp3'
	      #   Load   song  with   Mutagen
	      song_mut   =  MP3(song)
	      #   Get  song  Length
	      global  song_length
	      song_length  =  song_mut.info.length
	      #   Convert  to  Time  Format
	      converted_song_length  =  time.strftime('%M:%S',   time.gmtime(song_length))

	      #  Increase   current   time  by  1   second 
	      current_time   +=1

	      if   int(my_slider.get())  ==   int(song_length):
	      	         status_bar.config(text=f'Time  Elapsed:   {converted_song_length}       ')
	      elif   paused:
	      	         pass
	      elif   int(my_slider.get())  ==   int(current_time):
	      	         #   Update   Slider  To  position
	      	         slider_position   =  int(song_length)
	      	         my_slider.config(to=slider_position,   value=int(current_time))

	      else:
	      	         #   Update   Slider  To  position
	      	         slider_position   =  int(song_length)
	      	         my_slider.config(to=slider_position,   value=int(my_slider.get()))

	      	         #   convert  to   time  format
	      	         converted_current_time  =   time.strftime('%M:%S',   time.gmtime(int(my_slider.get())))

	      	         #   Output  time   to   status  bar
	      	         status_bar.config(text=f'Time  Elapsed:   {converted_current_time}     of   {converted_song_length}      ')

	      	         #   Move   this  thing   along   by   one  second
	      	         next_time   =  int(my_slider.get())   +   1
	      	         my_slider.config(value=next_time)





	     
	      #  Output   time   to  status   bar
	      #status_bar.config(text=f'Time  Elapsed:   {converted_current_time}     of   {converted_song_length}     ')

	      #  Update   slider   position  value   to  current   song   position...
	      #my_slider.config(value=int(current_time))

	      
	      #  update   time
	      status_bar.after(1000,   play_time)
def autoMatch(song_info_list, song_name, tags, song_with_path, test=0):
    for song in song_info_list:
        json_data = json.loads(json.dumps(song))

        #################################################
        if test:
            # print(json.dumps(json_data, indent=4))
            print()
            print(json_data['title'].lower().strip())
            print(song_name.lower().strip())
        #################################################

        song_name = song_name.lower().strip()
        title = json_data['title'].lower().strip()

        ed_title = tools.editDistDP(song_name, title, len(song_name), len(title))
        if test:
            print(ed_title)

        if ed_title > 5:
            continue

        if tools.isTagPresent(tags, 'album'):

            album_from_tags = tools.removeYear(tags['album'][0]).lower().strip()
            # try:
            #     album_from_json = json_data['actual_album'].lower().strip()
            # except KeyError:
            album_from_json = json_data['album'].lower().strip()
            ed_album = tools.editDistDP(album_from_tags, album_from_json, len(album_from_tags), len(album_from_json))

            if test:
                print(album_from_json)
                print(album_from_tags)
                print(ed_album)

            if ed_album > 4:
                continue

        if tools.isTagPresent(tags, 'artist'):
            artist_from_json = json_data['singers']
            artist_from_json = tools.divideBySColon(artist_from_json)
            artist_from_json = tools.removeTrailingExtras(artist_from_json)
            artist_from_json = tools.removeDup(artist_from_json)

            artist_from_tags = tags['artist'][0]
            artist_from_tags = tools.divideBySColon(artist_from_tags)
            artist_from_tags = tools.removeTrailingExtras(artist_from_tags)
            artist_from_tags = tools.removeDup(artist_from_tags)

            ed_artist = tools.editDistDP(artist_from_tags, artist_from_json, len(artist_from_tags),
                                         len(artist_from_json))

            if test:
                print(artist_from_json)
                print(artist_from_tags)
                print(ed_artist)

            if ed_artist >= 11:
                continue

        audio = MP3(song_with_path)
        length_from_tags = int(audio.info.length)
        length_from_json = int(json_data['duration'])

        if test:
            print(length_from_json)
            print(length_from_tags)
            print(mod(length_from_json) - length_from_tags)

        if mod(length_from_json - length_from_tags) > 10:
            continue

        return song

    return None
Example #24
0
def setData(SONG_INFO, is_quiet, song_path, choice=None):
    """Add the metadata to the song."""
    # A variable to see if cover image was added.
    IS_IMG_ADDED = False

    try:
        # If more than one choice then call getChoice
        if len(SONG_INFO) > 1:
            if not is_quiet:
                option = getChoice(SONG_INFO, 'metadata')
            elif choice is not None and choice in range(1,len(SONG_INFO)):
                option = choice
        else:
            option = 0

        SONG_PATH = os.path.join(defaults.DEFAULT.SONG_TEMP_DIR,
                                 song_path)

        audio = MP3(SONG_PATH, ID3=ID3)
        data = ID3(SONG_PATH)

        # Download the cover image, if failed, pass
        if dwCover(SONG_INFO, option):
            imagedata = open(defaults.DEFAULT.COVER_IMG, 'rb').read()
            data.add(APIC(3, 'image/jpeg', 3, 'Front cover', imagedata))
            # REmove the image
            os.remove(defaults.DEFAULT.COVER_IMG)
            IS_IMG_ADDED = True

        # If tags are not present then add them
        try:
            audio.add_tags()
        except Exception:
            pass

        audio.save()

        option = int(option)

        data.add(TYER(encoding=3, text=SONG_INFO[option].release_date))
        data.add(TIT2(encoding=3, text=SONG_INFO[option].track_name))
        data.add(TPE1(encoding=3, text=SONG_INFO[option].artist_name))
        data.add(TALB(encoding=3, text=SONG_INFO[option].collection_name))
        data.add(TCON(encoding=3, text=SONG_INFO[option].primary_genre_name))
        data.add(TRCK(encoding=3, text=str(SONG_INFO[option].track_number)))

        data.save()

        defaults.DEFAULT.SONG_NAME_TO_SAVE = SONG_INFO[option].track_name + '.mp3'

        # Rename the downloaded file
        os.rename(SONG_PATH, os.path.join(defaults.DEFAULT.SONG_TEMP_DIR,
                                             defaults.DEFAULT.SONG_NAME_TO_SAVE))

        # Show the written stuff in a better format
        prepend.PREPEND(1)
        print('================================')
        print('  || YEAR: ' + SONG_INFO[option].release_date)
        print('  || TITLE: ' + SONG_INFO[option].track_name)
        print('  || ARITST: ' + SONG_INFO[option].artist_name)
        print('  || ALBUM: ' + SONG_INFO[option].collection_name)
        print('  || GENRE: ' + SONG_INFO[option].primary_genre_name)
        print('  || TRACK NO: ' + str(SONG_INFO[option].track_number))

        if IS_IMG_ADDED:
            print('  || ALBUM COVER ADDED')

        prepend.PREPEND(1)
        print('================================')

        return option
    except Exception as e:
        # traceback.print_tb(e.__traceback__)
        return e
Example #25
0
    for f in (glob.glob(fold + "*.wav")):
        y, sr = librosa.load(f, duration=12.0)
        c1s = librosa.core.stft(y=y)
        c1c = librosa.feature.chroma_stft(y=y, sr=sr, n_chroma=88)
        c1s = np.vstack((c1s.real, c1s.imag))
        stft_shape = c1s.shape
        c1sr = np.reshape(c1s, (1, stft_shape[0], stft_shape[1], 1))
        chrom_shape = c1c.shape
        c1cr = np.reshape(c1c, (1, chrom_shape[0], chrom_shape[1], 1))
        lap_stft = lap_pyramid(6, stft_shape)
        lap_chrom = lap_pyramid(6, chrom_shape)
    stft_lap_temp, stft_eucl_temp, chrom_lap_temp, \
            chrom_eucl_temp, bitrates = [], [], [], [], []
    for f in (glob.glob(fold + "*.mp3")):
        y2, sr2 = librosa.load(f, duration=12.0)
        m = MP3(f)
        bitrates.append(m.info.bitrate / 1000)

        # STFT
        stft = librosa.core.stft(y=y2)
        stft = np.vstack((stft.real, stft.imag))
        stftr = np.reshape(stft, (1, stft_shape[0], stft_shape[1], 1))
        stft_lap_temp.append(lap_stft.compare(c1sr, stftr))
        stft_eucl_temp.append(abs(np.sqrt(np.mean((c1s - stft)**2))))

        # Chrom
        chrom = librosa.feature.chroma_stft(y=y2, sr=sr2, n_chroma=88)
        chromr = np.reshape(chrom, (1, chrom_shape[0], chrom_shape[1], 1))
        chrom_lap_temp.append(lap_chrom.compare(c1cr, chromr))
        chrom_eucl_temp.append(np.sqrt(np.mean((c1c - chrom)**2)))
Example #26
0
import mp3play
from mutagen.mp3 import MP3
import sys
import time

f = "audio.mp3"
audio = MP3(f)
length = audio.info.length
clip = mp3play.load(f)
clip.play()
time.sleep(length)
clip.stop()
Example #27
0
def download(textToSearch, est_time, image_url, spotify_data):
    class MyLogger(object):
        def debug(self, msg):
            pass

        def warning(self, msg):
            pass

        def error(self, msg):
            print(msg)

    def my_hook(d):
        if d['status'] == 'finished':
            #print('Done downloading, now converting ...')
            pass

    def absoluteFilePaths(directory):
        paths = []
        for root, dirs, files in os.walk(os.path.abspath("../path/to/dir/")):
            for file in files:
                #print(os.path.join(root, file))
                paths.append(os.path.join(root, file))
        return paths

    soup = search_youtube(textToSearch)
    vids = soup.findAll(attrs={'class': 'yt-uix-tile-link'})
    times = soup.findAll(attrs={'class': "video-time"})

    #for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
    #    pass
    #print vid['title']

    i = 0
    found_appropriate_video = False
    while found_appropriate_video == False:
        title = vids[i]['title']
        lower_title = title.lower()
        found_appropriate_video = True
        if "official music video" in title or 'official video' in lower_title:
            print("FOUND OFFICIAL MUSIC VIDEO")
            # Recursive call, String now excludes music video phrase
            found_appropriate_video = False
            i += 1
        time_string = str(times[i].next)
        if len(time_string) <= 5:

            print(time_string)
            run_time = get_sec(time_string)
            # print "Time  of vid is: ",   run_time
            # print "Estimated Time is: ", est_time

            difference = int(run_time) - int(est_time)
            if difference < 0:
                difference = difference * -1
            if difference > 60:
                #print("THIS VIDEO IS NOT THE RIGHT LENGTH")
                #print(difference,run_time,est_time)
                #return
                i += 1
                found_appropriate_video = False
        else:
            i += 1
    di = i
    print "Name of video I'm downloading is: ", title
    i = 0

    ydl_opts = {
        'format':
        'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '320',
        }],
        'logger':
        MyLogger(),
        'progress_hooks': [my_hook],
    }

    cwd = os.getcwd()
    current_dir = cwd
    print("CURRNENT DIRECTORY ", cwd)
    title = title.replace('"', "'")
    vid_path = 'https://www.youtube.com' + vids[di]['href']
    onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]
    print("DESITNATION OF VIDEO", title)
    if title + '.mp3' not in onlyfiles:
        if not os.path.isdir('tmp'):
            os.mkdir('tmp')
        os.chdir('tmp')
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([vid_path])
        try:
            #f = open(title+'_image.jpeg', 'wb')
            #f.write(urllib.urlopen(image_url).read())
            #f.close()
            pass
        except:

            print('filename error, couldnt write image')

        #f = open(title + '_image.jpeg', 'wb')
        #image_url = 'webfiles/' +title + '_image.jpeg'
        #f.write(urllib.urlopen(image_url).read())
        #f.close()
        tmp_files = [
            f for f in listdir(cwd + '/tmp') if isfile(join(cwd + '/tmp', f))
        ]

        for l in range(0, len(tmp_files)):
            print(tmp_files[l])
            print('.mp3' in tmp_files[l])
            if '.mp3' in tmp_files[l]:
                title = tmp_files[l]

        audio = MP3(title, ID3=ID3)

        # add ID3 tag if it doesn't exist
        try:
            audio.add_tags()
        except error:
            pass
        tmp_files = [
            f for f in listdir(cwd + '/tmp') if isfile(join(cwd + '/tmp', f))
        ]

        for l in range(0, len(tmp_files)):
            print(tmp_files[l])
            print('.jpeg' in tmp_files[l])
            if '.jpeg' in tmp_files[l]:
                image_path = tmp_files[l]

        image_path = cwd[:len(cwd) -
                         len('songs/')] + '/webfiles/' + spotify_data[
                             'title'] + '_image.jpeg'
        audio.tags.add(
            APIC(
                encoding=3,  # 3 is for utf-8
                mime='image/png',  # image/jpeg or image/png
                type=3,  # 3 is for the cover image
                desc=u'Cover',
                data=open(image_path).read()))
        audio.save()
        try:
            audio = EasyID3(title)
        except:
            pass
            print("PROBLEM")
        try:
            #print(spotify_data['tracknumber'])
            audio['tracknumber'] = int(spotify_data['tracknumber'])
        except:
            pass
            #print "Couldn't Insert tracknumber"
        audio['artist'] = str(spotify_data['artist'])
        audio['title'] = str(spotify_data['title'])
        audio['album'] = str(spotify_data['album'])
        try:
            audio['tempo'] = spotify_data["tempo"]
        except:
            pass
        audio.save()
        #        os.remove(cwd+'/tmp/'+image_path)

        try:
            tags = ID3(title)
            tags['TRCK'] = TRCK(encoding=3,
                                text=str(spotify_data['tracknumber']))
        except ID3NoHeaderError:
            print "Adding ID3 header;",
            tags = ID3()
        tags.save()
        print(cwd + '/tmp/' + title)

        print("putting file")
        print(current_dir)
        os.rename(current_dir + '/tmp/' + title, current_dir + '/' + title)
        os.chdir(current_dir)
Example #28
0
def music_line():
    global num_music, peremotka, text_x, povtor_on, music_time_now_test

    if len(music_list) > 0:

        keys = pygame.key.get_pressed()

        #tracking current song length and full song length
        try:
            music_time = MP3(music_list[num_music]).info.length
            music_time_now = music_time_now_test + round(
                pygame.mixer.music.get_pos() / 1000, 2)
        except Exception:
            num_music += peremotka
            decore()

        pos = pygame.mouse.get_pos()
        mouse_x, mouse_y = pos[0], pos[1]
        MOUSE_CLICK = pygame.mouse.get_pressed()

        #percentage to fill the progress bar
        proc = music_time / 100
        proc = round(music_time_now / proc)
        proc = proc * 2
        music_line_round_x = 20 + proc

        pygame.draw.rect(win, (104, 104, 104), (20, 270, 200, 5))
        pygame.draw.circle(win, (255, 0, 0), (music_line_round_x, 272), 8)

        #tracking the end of a track
        if round(music_time_now) >= math.floor(music_time):
            music_time_now_test = 0
            if povtor_on == True:
                peremotka = 0
            num_music += peremotka
            text_x = 10
            play_music()

        if music_line_round_x > 20:
            pygame.draw.rect(win, (255, 0, 0),
                             (20, 270, music_line_round_x - 20, 5))

        #setting a track at a specific second
        if mouse_x >= 20 and mouse_x <= 220 and mouse_y >= 265 and mouse_y <= 275:
            procen = (mouse_x - 20)
            procen = procen * music_time / 100 / 2

            secondes3 = timedelta(seconds=procen)
            timer3 = datetime(1, 1, 1) + secondes3
            print_text(
                str(timer3.minute) + ":" + str(timer3.second), mouse_x - 20,
                255)

            if MOUSE_CLICK[0] == 1:
                music_time_now_test = procen
                music_time_now = music_time_now_test + round(
                    pygame.mixer.music.get_pos() / 1000 / 60, 2)

                pygame.mixer.music.stop()
                pygame.mixer.music.play(-1, round(procen))
                time.sleep(0.2)

        try:
            secondes1 = timedelta(seconds=music_time_now)
            timer1 = datetime(1, 1, 1) + secondes1

            secondes2 = timedelta(seconds=music_time)
            timer2 = datetime(1, 1, 1) + secondes2

            print_text(str(timer1.minute) + ":" + str(timer1.second),
                       20,
                       278,
                       font_size=15)
            print_text(str(timer2.minute) + ":" + str(timer2.second),
                       200,
                       278,
                       font_size=15)
        except OverflowError:
            pass
Example #29
0
def play_time():
	# Check for double timing
	if stopped:
		return
	# Get current song elapsed time
	current_time = pygame.mixer.music.get_pos() / 1000

	# Throw up temp. lable to get data
	# slider_label.config(text=f'Slider: {int(my_slider.get())} and Song Pos: {int(current_time)}')

	# Conver to time format
	converted_current_time = time.strftime('%M:%S', time.gmtime(current_time))

	# Get the currently playing song
	#current_song = list_box.curselection()
	# Grab song title from playlist
	song = list_box.get(ACTIVE)
	# Add directory structure and mp3 to song name
	song = f'C:/Users/ansha/Desktop/summer_project/gui/audio/{song}.mp3'
	# Load song with mutagen
	song_mut = MP3(song)
	# Get song length
	global song_length
	song_length = song_mut.info.length
	# Convert to time format
	converted_song_length = time.strftime('%M:%S', time.gmtime(song_length))

	# Increase current time by one second
	current_time += 1

	if int(my_slider.get()) == int(song_length):
		pass
		status_bar.config(text=f'Time Elapsed: {converted_song_length}  ')

	elif paused:
		pass

	elif int(my_slider.get()) == int(current_time):
		# update slider to position
		slider_position = int(song_length)
		my_slider.config(to=slider_position, value=int(current_time))
	else:
		# update slider to position
		slider_position = int(song_length)
		my_slider.config(to=slider_position, value=int(my_slider.get()))
		
		# Conver to time format
		converted_current_time = time.strftime('%M:%S', time.gmtime(int(my_slider.get())))
	
		# Output time to status bar
		status_bar.config(text=f'Time Elapsed: {converted_current_time}  of  {converted_song_length}  ')

		# Move this thing along by one sec
		next_time = int(my_slider.get()) + 1
		my_slider.config(value=next_time)

	# # Output time to status bar
	# status_bar.config(text=f'Time Elapsed: {converted_current_time}  of  {converted_song_length}  ')
	
	# Update slider position valur to current time position
	#my_slider.config(value=int(current_time))

	

	# update time
	status_bar.after(1000, play_time)
Example #30
0
def download_songs(songs,
                   download_directory,
                   format_string,
                   skip_mp3,
                   keep_playlist_order=False):
    """
    Downloads songs from the YouTube URL passed to either current directory or download_directory, is it is passed.
    :param songs: Dictionary of songs and associated artist
    :param download_directory: Location where to save
    :param format_string: format string for the file conversion
    :param skip_mp3: Whether to skip conversion to MP3
    :param keep_playlist_order: Whether to keep original playlist ordering. Also, prefixes songs files with playlist num
    """
    log.debug(f"Downloading to {download_directory}")
    for song in songs:
        query = f"{song.get('artist')} - {song.get('name')} Lyrics".replace(
            ":", "").replace("\"", "")
        download_archive = path.join(download_directory,
                                     'downloaded_songs.txt')

        file_name = sanitize(f"{song.get('artist')} - {song.get('name')}",
                             '#')  # youtube-dl automatically replaces with #
        if keep_playlist_order:
            # add song number prefix
            file_name = f"{song.get('playlist_num')} - {file_name}"
        file_path = path.join(download_directory, file_name)

        outtmpl = f"{file_path}.%(ext)s"
        ydl_opts = {
            'format':
            format_string,
            'download_archive':
            download_archive,
            'outtmpl':
            outtmpl,
            'default_search':
            'ytsearch',
            'noplaylist':
            True,
            'postprocessor_args': [
                '-metadata', 'title=' + song.get('name'), '-metadata',
                'artist=' + song.get('artist'), '-metadata',
                'album=' + song.get('album')
            ]
        }
        if not skip_mp3:
            mp3_postprocess_opts = {
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }
            ydl_opts['postprocessors'] = [mp3_postprocess_opts.copy()]

        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            try:
                ydl.download([query])
            except Exception as e:
                log.debug(e)
                print(
                    'Failed to download: {}, please ensure YouTubeDL is up-to-date. '
                    .format(query))
                continue

        if not skip_mp3:
            song_file = MP3(path.join(f"{file_path}.mp3"), ID3=EasyID3)
            song_file['date'] = song.get('year')
            if keep_playlist_order:
                song_file['tracknumber'] = str(song.get('playlist_num'))
            else:
                song_file['tracknumber'] = str(song.get('num')) + '/' + str(
                    song.get('num_tracks'))
            song_file['genre'] = song.get('genre')
            song_file.save()
            song_file = MP3(path.join(
                download_directory,
                f"{song.get('artist')} - {song.get('name')}.mp3"),
                            ID3=ID3)
            if song.get('cover') is not None:
                song_file.tags['APIC'] = APIC(encoding=3,
                                              mime='image/jpeg',
                                              type=3,
                                              desc=u'Cover',
                                              data=urllib.request.urlopen(
                                                  song.get('cover')).read())
            song_file.save()
Example #31
0
	def __init__(self, *args, **kwargs):
		kwargs['ID3'] = EasyID3
		MP3.__init__(self,*args, **kwargs)
Example #32
0
def music_line(win):
	global num_music, music_time_now_test, text_x, peremotka, povtor_on, music_list

	if len(music_list) > 0:

		name_dict = os.getenv('USERPROFILE')
		path_music = name_dict + '\\OnlineMusic\\'

		try:
			path_save_url = path_music + music_list[num_music].get('name')
			music_load = path_save_url + '.mp3'
		except IndexError:
			music_list = []


		#tracking current song length and full song length
		try:
			music_time = MP3(music_load).info.length
			music_time_now = music_time_now_test + round(pygame.mixer.music.get_pos() / 1000, 2)
		except Exception:
			num_music += peremotka
			OnlineMusic.play_music()


		pos = pygame.mouse.get_pos()
		mouse_x, mouse_y = pos[0], pos[1]
		MOUSE_CLICK = pygame.mouse.get_pressed()

		#percentage to fill the progress bar
		try:
			proc = music_time / 100
			proc = round(music_time_now / proc )
			proc = proc * 2
			music_line_round_x = 20 + proc
		except UnboundLocalError:
			music_time = 0
			music_time_now = 0
			music_line_round_x = 20



		pygame.draw.rect(win,(104,104,104), (20, 270,200,5))
		pygame.draw.circle(win,(255,0,0),(music_line_round_x, 272), 8)


		#tracking the end of a track
		if round(music_time_now) >= math.floor(music_time):
			music_time_now_test = 0
			if povtor_on == True:
				peremotka = 0
			num_music += peremotka
			text_x = 10
			OnlineMusic.play_music()


		if music_line_round_x > 20:
			pygame.draw.rect(win, (255,0,0), (20, 270,music_line_round_x - 20 , 5))

		#setting a track at a specific second
		if mouse_x >= 20 and mouse_x <= 220 and mouse_y >= 265 and mouse_y <= 275:
			procen = (mouse_x - 20)
			procen = procen * music_time / 100 / 2

			secondes3 = timedelta(seconds=procen)
			timer3 = datetime(1,1,1) + secondes3
			print_text(win, str(timer3.minute) + ":" + str(timer3.second), mouse_x - 20, 255)

			if MOUSE_CLICK[0] == 1:
				music_time_now_test = procen
				music_time_now = music_time_now_test + round(pygame.mixer.music.get_pos() / 1000 / 60, 2)

				pygame.mixer.music.stop()
				pygame.mixer.music.play(-1,round(procen))
				time.sleep(0.2)

		#time stamp
		try:
			secondes1 = timedelta(seconds=music_time_now)
			timer1 = datetime(1,1,1) + secondes1

			secondes2 = timedelta(seconds=music_time)
			timer2 = datetime(1,1,1) + secondes2

			print_text(win, str(timer1.minute) + ":" + str(timer1.second), 20, 278, font_size = 15)
			print_text(win, str(timer2.minute) + ":" + str(timer2.second), 200, 278, font_size=15)
		except OverflowError:
			pass