MP3 Player Song Duration and Length Python Tkinter GUI - learnit

Home Top Ad

Post Top Ad

Friday, June 4, 2021

MP3 Player Song Duration and Length Python Tkinter GUI

MP3 Player Song Duration and Length Python Tkinter GUI

What is Python

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python is simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.


Often, programmers fall in love with Python because of the increased productivity it provides. Since there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault. Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace. A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on. The debugger is written in Python itself, testifying to Python's introspective power. On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.


MP3 Player Song Duration and Length Python Tkinter GUI

Before starting to show coding, let me introduce you to Mutagen in Python, what is Mutagen ??


Mutagen is a Python module to handle audio metadata. It supports ASF, FLAC, MP4, Monkey’s Audio, MP3, Musepack, Ogg Opus, Ogg FLAC, Ogg Speex, Ogg Theora, Ogg Vorbis, True Audio, WavPack, OptimFROG, and AIFF audio files. All versions of ID3v2 are supported, and all standard ID3v2.4 frames are parsed. It can read Xing headers to accurately calculate the bitrate and length of MP3s. ID3 and APEv2 tags can be edited regardless of audio format. It can also manipulate Ogg streams on an individual packet/page level.


Mutagen works with Python 3.5+ (CPython and PyPy) on Linux, Windows and macOS, and has no dependencies outside the Python standard library. Mutagen is licensed under the GPL version 2 or later.


In this video we'll get the song duration and the total song length for our MP3 songs in our MP3 playlist!


Pygame makes getting the current position of a song (it's duration) pretty easy, but it doesn't have any mechanism to find out an mp3 files total length.


So we'll install something called Mutagen to get our MP3 song lengths, then we'll output both the song duration and length onto a status bar at the bottom of our mp3 player that updates as the song plays.


Example

from tkinter import *
import pygame
from tkinter import filedialog
import time
from mutagen.mp3 import MP3
root= Tk()
root.title('reanits.blogspot.com')
root.iconbitmap('1.png')
root.geometry('300x400')
pygame.mixer.init()
def playtime():
    Currenttime = pygame.mixer.music.get_pos()/1001
    Covertedcurrenttime = time.strftime('%M:%S',time.gmtime(Currenttime))
    #statusbar.config(text=int(Currenttime))
    statusbar.config(text=Covertedcurrenttime)
    statusbar.after(1000,playtime)
    song = songbox.get(ACTIVE)
    song = f'D:/Python/Test2/sound/{song}.mp3
    songmut= MP3(song)
    songlength=songmut.info.length
    coverntedcurrentlength = time.strftime('%M:%S', time.gmtime(songlength))
    statusbar.config(text=f'Time Elapsed: {Covertedcurrenttime} of {coverntedcurrentlength} ')
    statusbar.after(1000, playtime)
def deletesongmusic():
  songbox.delete(ANCHOR
  pygame.mixer.music.stop()
def deletesongsmusics():
  songbox.delete(0,END)
  pygame.mixer.music.stop()
def addsongmusic():
  song = filedialog.askopenfilename(initialdir='sound/', title="Choose File Song", filetypes=(("MP3 file", "*.mp3"),))
  song = song.replace("D:/Python/Test2/sound/","")
  song = song.replace(".mp3", "")
  songbox.insert(END,song)
def addsongsmusic():
  songs = filedialog.askopenfilenames(initialdir='sound/', title="Choose File Song", filetypes=(("MP3 file", "*.mp3"),))
  for song in songs:
    song = song.replace("D:/Python/Test2/sound/", "")
    song = song.replace(".mp3", "")
    songbox.insert(END, song)
def playmusic():
  song = songbox.get(ACTIVE)
  song = f'D:/Python/Test2/sound/{song}.mp3'
  pygame.mixer.music.load(song)
  pygame.mixer.music.play(loops=0)
  playtime()
def stopmusic():
  pygame.mixer.music.stop()
  songbox.select_clear(ACTIVE)
  statusbar.config(text='')
def nextmusic():
  nextone = songbox.curselection()
  nextone = nextone[0]+1
  song = songbox.get(nextone)
  song = f'D:/Python/Test2/sound/{song}.mp3'
  pygame.mixer.music.load(song)
  pygame.mixer.music.play(loops=0)
  songbox.select_clear(0,END)
  songbox.activate(nextone)
  songbox.selection_set(nextone, last=None)
def preback():
  nextone = songbox.curselection()
  nextone = nextone[0] - 1
  song = songbox.get(nextone)
  song = f'D:/Python/Test2/sound/{song}.mp3'
  pygame.mixer.music.load(song)
  pygame.mixer.music.play(loops=0)
  songbox.select_clear(0, END)
  songbox.activate(nextone)
  songbox.selection_set(nextone, last=None)
global paused
paused = False
def pause(is_paused):
  global paused
  paused = is_paused
  if paused:
    pygame.mixer.music.unpause()
    paused = False
  else:
    pygame.mixer.music.pause()
    paused = True
songbox= Listbox(root, bg="black", fg="green", width=80,selectbackground="gray",selectforeground="black")
songbox.pack(pady=20)
backbtn= PhotoImage(file='image/forward101.png')
forwardbtn= PhotoImage(file='image/forward101.png')
playbtn= PhotoImage(file='image/Play101.png')
pausebtn= PhotoImage(file='image/pause101.png')
stopbtn= PhotoImage(file='image/Stop101.png')
controlframe= Frame(root)
controlframe.pack()
backbutton= Button(controlframe, image=backbtn, borderwidth=0, command=preback)
frowardbutton= Button(controlframe, image=forwardbtn, borderwidth=0,command=nextmusic)
playbutton= Button(controlframe, image=playbtn, borderwidth=0, command=playmusic)
pausebutton= Button(controlframe, image=pausebtn, borderwidth=0, command=lambda: pause(paused))
stopbutton= Button(controlframe, image=stopbtn, borderwidth=0, command=stopmusic)
backbutton.grid(row=0, column=1, padx=10)
frowardbutton.grid(row=0, column=2, padx=20)
playbutton.grid(row=0, column=3, padx=20)
pausebutton.grid(row=0, column=4, padx=20)
stopbutton.grid(row=0, column=5, padx=20)
#create Menu
mymenu = Menu(root)
root.config(menu=mymenu)
addsong = Menu(mymenu)
mymenu.add_cascade(label="file", menu=addsong)
addsong.add_command(label="Open Song or Playlist",command=addsongmusic)
addsong.add_command(label="Open Many Songs or Playlist",command=addsongsmusic)
deletesong = Menu(mymenu)
mymenu.add_cascade(label="Delete", menu=deletesong)
deletesong.add_command(label="Delete Song or Playlist",command=deletesongmusic)
deletesong.add_command(label="Delete All Songs or Playlist",command=deletesongsmusics)
statusbar= Label(root, text='',bd=1, relief=GROOVE, anchor=E)
statusbar.pack(fill=X,side=BOTTOM, ipady=2)
root.mainloop()

Please Watching My Video is Below







82 comments:

  1. After study some of the websites with your web site now, we truly as if your technique for blogging. I bookmarked it to my bookmark site list and will be checking back soon. Pls look into my website also and told me what you consider. pagalworld com

    ReplyDelete
  2. When I originally commented I clicked the -Notify me when new comments are added- checkbox and today each time a comment is added I purchase four emails sticking with the same comment. Can there be however you may get rid of me from that service? Thanks! pagalworld mp3 songs a to z

    ReplyDelete
  3. Obviously you can pull off not having the option to coordinate with Adele's vocal quality and still please your crowd in case you're a six year old young lady singing this melody with everything that is in you, as did Alexa Narvaez on YouTube with at present more than 13 million perspectives.) youtube to mp3

    ReplyDelete
  4. There has not been any a case of a LiPo battery bursting into flames while in storage. The fire accidents involving LiPo batteries often happen during the battery's charge or discharge. flexible battery

    ReplyDelete
  5. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging The Best Line Dance Songs for Weddings

    ReplyDelete
  6. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. wheels

    ReplyDelete
  7. I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. https://vegamovies.today

    ReplyDelete
  8. Hello, this weekend is good for me, since this time i am reading this enormous informative article here at my home. https://kuttymovies.website

    ReplyDelete
  9. You understand your projects stand out of the crowd. There is something unique about them. It seems to me all of them are brilliant. https://movieswood.today

    ReplyDelete
  10. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. https://pedropolis.site

    ReplyDelete
  11. Thank you for this fascinating post, I am happy I observed this website on Google. Not just content, in fact, the whole site is fantastic. https://123mkv.website

    ReplyDelete
  12. Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts. https://putlocker-live.org

    ReplyDelete
  13. This was a really great contest and hopefully I can attend the next one. It was alot of fun and I really enjoyed myself.. https://megashare-website.com

    ReplyDelete
  14. Thanks for the blog filled with so many information. Stopping by your blog helped me to get what I was looking for. Now my task has become as easy as ABC. https://himovies.live

    ReplyDelete
  15. If you are looking for more information about flat rate locksmith Las Vegas check that right away. https://primewire.today

    ReplyDelete
  16. Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. https://watchserieshd.live

    ReplyDelete
  17. I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work. https://primewire-movies.com

    ReplyDelete
  18. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free https://xmovies8.one

    ReplyDelete
  19. Nice post. I was checking constantly this blog and I’m impressed! Extremely useful info specially the last part I care for such information a lot. I was seeking this certain info for a long time. Thank you and good luck.  https://vexmovies.pw

    ReplyDelete
  20. Excellent post. I was always checking this blog, and I’m impressed! Extremely useful info specially the last part, I care for such information a lot. I was exploring this particular info for a long time. Thanks to this blog my exploration has ended. https://putlocker.quest

    ReplyDelete
  21. Very useful post. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. Really its great article. Keep it up. https://onlinemovie25.com

    ReplyDelete
  22. preview of the movie in the form either of a short extract or the official trailer. https://123cima4u.com/

    ReplyDelete
  23. I know this is one of the most meaningful information for me. And I'm animated reading your article. But should remark on some general things, the website style is perfect; the articles are great. Thanks for the ton of tangible and attainable help. https://vumoo.vip

    ReplyDelete
  24. A great content material as well as great layout. Your website deserves all of the positive feedback it’s been getting. I will be back soon for further quality contents. https://afdah.space

    ReplyDelete
  25. I am incapable of reading articles online very often, but I’m happy I did today. It is very well written, and your points are well-expressed. I request you warmly, please, don’t ever stop writing. https://aafdah.org

    ReplyDelete
  26. I am thankful to you for sharing this plethora of useful information. I found this resource utmost beneficial for me. Thanks a lot for hard work. https://thecouchtuner.space

    ReplyDelete
  27. Thank you so much as you have been willing to share information with us. We will forever admire all you have done here because you have made my work as easy as  https://couchtunerweb.site

    ReplyDelete
  28. Great survey, I'm sure you're getting a great response https://newcouchtuner.site

    ReplyDelete
  29. Succeed! It could be one of the most useful blogs we have ever come across on the subject. Excellent info! I’m also an expert in this topic so I can understand your effort very well. Thanks for the huge help. https://123moviesite.one

    ReplyDelete
  30. I have a hard time describing my thoughts on content, but I really felt I should here. Your article is really great. I like the way you wrote this information https://couchtuner.quest

    ReplyDelete
  31. I can’t believe focusing long enough to research; much less write this kind of article. You’ve outdone yourself with this material without a doubt. It is one of the greatest contents. https://the123movies.site

    ReplyDelete
  32. Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though. https://soap2daymovies.website

    ReplyDelete
  33. {السينما للجميع | Cima4u } cima4u | السينما للجميع لمشاهدة الافلام و المسلسلات الحصريه مشاهدة اجدد افلام اون لاين عربي و اجنبي مترجم جميع حلقات المسلسلات حصرية مباشرة مشاهدة افلام البوكس اوفيس حصرياً اون لاين بجودة عالية مباشرة .

    ReplyDelete
  34. Stylish folks create, the important points could be very helpful as well as beneficial, We are going to offer web page link for the website. mp3xd

    ReplyDelete
  35. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. https://soap2daymovies.site

    ReplyDelete
  36. Wow, excellent post. I'd like to draft like this too - taking time and real hard work to make a great article. This post has encouraged me to write some posts that I am going to write soon. https://123moviesnow.space

    ReplyDelete
  37. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work https://putlocker-movies.space

    ReplyDelete
  38. I visit your blog regularly and recommend it to all of those who wanted to enhance their knowledge with ease. The style of writing is excellent and also the content is top-notch. Thanks for that shrewdness you provide the readers! https://la-123movies.one

    ReplyDelete
  39. I found that site very usefull and this survey is very cirious, I ' ve never seen a blog that demand a survey for this actions, very curious https://soap2day.shop

    ReplyDelete
  40. Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive https://soap2day.monster

    ReplyDelete
  41. I would like to say that this blog really convinced me to do it! Thanks, very good post. https://solarmovies.space

    ReplyDelete
  42. Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. https://soaptoday.website

    ReplyDelete
  43. Your blog is too much amazing. I have found with ease what I was looking. Moreover, the content quality is awesome. Thanks for the nudge! https://movies123.win

    ReplyDelete
  44. I know this is one of the most meaningful information for me. And I'm animated reading your article. But should remark on some general things, the website style is perfect; the articles are great. Thanks for the ton of tangible and attainable help. https://the123movies.top

    ReplyDelete
  45. Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post.
    https://watchcouchtuner.website

    ReplyDelete
  46. Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive https://watchcouchtuner.space

    ReplyDelete
  47. Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive https://theprimewire.site/

    ReplyDelete
  48. I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business. https://theprimewire.website

    ReplyDelete
  49. Wow, cool post. I’d like to write like this too – taking time and real hard work to make a great article… but I put things off too much and never seem to get started. Thanks though. Initia Tourist Visisa

    ReplyDelete
  50. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. Turkiyaga viza olish uchun ariza

    ReplyDelete
  51. We have sell some products of different custom boxes.it is very useful and very low price please visits this site thanks and please share this post with your friends. USA VISA ONLINE

    ReplyDelete
  52. Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. FÅ OFFISIELL INDIAN VISA

    ReplyDelete
  53. For many people, this is the best solution here see how to do it. INDIA MEDICAL VISA

    ReplyDelete
  54. This is very interesting content! I have thoroughly enjoyed reading your points and have come to the conclusion that you are right about many of them. You are great. 먹튀검증

    ReplyDelete
  55. Music darlings! MP3 tune authorities! Pondering where to track down a free duplicate of that main tune? Assuming that you're understanding this, https://www.spotifyfame.com/

    ReplyDelete
  56. Very good written article. It will be supportive to anyone who utilizes it, including me. Keep doing what you are doing – can’r wait to read more posts. कनाडा वीजा आवेदन

    ReplyDelete
  57. It’s appropriate time to make some plans for the future and it is time to be happy. I have read this post and if I could I wish to suggest you few interesting things or advice. Perhaps you could write next articles referring to this article. I desire to read even more things about it! Visto Canada ETA

    ReplyDelete
  58. Thank you so much for sharing this great blog.Very inspiring and helpful too.Hope you continue to share more of your ideas.I will definitely love to read. 꽁머니

    ReplyDelete
  59. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. Canada Visa for Czech Citizens

    ReplyDelete
  60. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. Wiza turystyczna do Indii

    ReplyDelete
  61. Great articles and great layout. Your blog post deserves all of the positive feedback it’s been getting. 找房子

    ReplyDelete
  62. This is just the information I am finding everywhere. Thanks for your blog, I just subscribe your blog. This is a nice blog.. 小額借款

    ReplyDelete
  63. Please continue this great work and I look forward to more of your awesome blog posts. 토토사이트

    ReplyDelete
  64. Webhosting ist ein Online-Dienst, der die Inhalte Ihrer Website im Internet zugänglich macht. Wenn Sie einen Hosting-Plan kaufen, mieten Sie Speicherplatz auf einem physischen Server, um alle Dateien und Daten der Website zu speichern.

    Webhoster stellen die Technologie und Ressourcen bereit, die für den effektiven und sicheren Betrieb Ihrer Website erforderlich sind. Sie sind dafür verantwortlich, den Server am Laufen zu halten, Sicherheitsmaßnahmen zu implementieren und sicherzustellen, dass Daten wie Texte, Fotos und andere Dateien erfolgreich an die Browser der Besucher übertragen werden.

    In diesem Artikel erfahren Sie, was Webhosting ist, wie es funktioniert und welche verschiedenen Arten von Webhosting verfügbar sind.
    Kredit Rechner

    ReplyDelete
  65. Fabulous post, you have denoted out some fantastic points, I likewise think this s a very wonderful website. I will visit again for more quality contents and also, recommend this site to all. Thanks. http://www.Starvegasvip.com

    ReplyDelete
  66. Thanks for the blog filled with so many information. Stopping by your blog helped me to get what I was looking for. Now my task has become as easy as ABC. sports betting portugal

    ReplyDelete
  67. I read this article. I think You put a lot of effort to create this article. I appreciate your work. 먹튀검증

    ReplyDelete
  68. This is helpful, nonetheless, it can be crucial so that you can check out the following website: shopping best choice

    ReplyDelete
  69. So a lot to occur over your amazing blog. Your blog procures me a fantastic transaction of enjoyment. Salubrious lot beside the scene. cool dog facts

    ReplyDelete
  70. It's superior, however, check out material at the street address. สล็อต pg

    ReplyDelete
  71. When your website or blog goes live for the first time, it is exciting. That is until you realize no one but you and your. Ice Cream Bakeries In Georgia

    ReplyDelete
  72. This is very interesting content! I have thoroughly enjoyed reading your points and have concluded that you are right about many of them. You are great. สล็อตแตกง่าย

    ReplyDelete
  73. Looking at the rankings of P2P sites is also a hobby! Everyone wants to enjoy their own hobbies , but it is not easy to find a suitable one. There are many hobbies, but due to time, cost, and location restrictions, there are many cases where you cannot do what you want when you want. As smartphones become more common, many have naturally switched from offline to online, so if you look closely at the P2P site rankings, it will be helpful to know that there are some that are possible without these restrictions. However, if it is a game where money is actually transferred, safety is also important, so if you only pay attention to this part and enjoy your hobby, there is not much to worry about p2p사이트 추천

    ReplyDelete
  74. Дигиталният маркетинг е процес на използване на онлайн канали за популяризиране и продажба на продукти или услуги. Той включва създаване на маркетингова стратегия, която отчита специфичните нужди на целевата аудитория, и след това използване на цифрови инструменти за достигане до тези клиенти. Това може да включва всичко - от създаване на уебсайт до разработване на целеви реклами и управление на акаунти в социалните медии. Целта на дигиталния маркетинг е да достигне до потенциалните клиенти там, където те прекарват времето си онлайн, и след това да ги превърне в платежоспособни клиенти. За да бъдат успешни, предприятията трябва да инвестират в цялостна стратегия за цифров маркетинг, която да отчита всички тези фактори. С правилния подход дигиталният маркетинг може да бъде ефективен начин за достигане до нови клиенти и за развитие на бизнеса. дигитален маркетинг

    ReplyDelete
  75. howdy, your websites are really good. I appreciate your work. BRITISH COLUMBIA FAKE DRIVERS LICENSE

    ReplyDelete
  76. I use superior fabrics: you will discover these products by: situs slot bonus 100

    ReplyDelete
  77. Welcome To MyToolsTown Instagram Auto Liker, Auto Comments & Auto Followers. A Website Made for those people who want to gain fame on instagram by getting a lot of likes, followers & comments. How Do We Make "FREE" Possible? Same as you, lots of real & active instagram users gather here to like and follow each other. Everyone earn credits by Liking & Following others. You also earn this credits and You can use them to get Likes & Followers on your Instagram account & posts. We have created the Best Instagram auto liker website which you can use to get unlimited auto likes, auto followers and awesome auto comments on your instagram for totally free. auto liker instagram

    ReplyDelete
  78. Anna Kubiak has been working in men's hairdressing for over twenty years, she comes from a hairdressing family and the beauty industry. Effectively combines professional experience with the latest trends, fashion, classic and avant-garde. We create new hairstyles for fathers, sons and grandparents. We have been working in men's hairdressing for many years, we have trained many talented hairdressers. Every day we change your image, improve your mood, we take care of your beard and mustache. We take care of your appearance, we combine classic, typical hairdressing craftsmanship with modernity. We have participated in several TV projects, we are open-minded and creative. “Do I have any way of dealing with women? Hmm, let's see. Money is a good thing. Money, fame and a good car: my unfailing holds. I have the impression that soon I will need them more and more, otherwise no one will even look at me. You know, year olds are flying, hair turns gray ... Modne fryzury męski Warszawa

    ReplyDelete
  79. I am absolutely thrilled with my recent purchase of the Ultra Air Heater! This innovative heating solution has exceeded my expectations in every way possible. Not only ultra air heater does it provide quick and efficient warmth to my living space, but its sleek design also adds a touch of modern elegance to my home.

    ReplyDelete

Post Top Ad