I'm super new to coding. I had a random idea in the car to make this application in order dive head first into learning to code.
This is an app to take an MP3 file, "shred it" into pieces (creates 1 second mp3 files temporarily), then randomize the pieces, and then compiles a new MP3 file with all the "shreds" in a randomized order. In order to accomplish this, I used my very limited knowledge and so my code probably isn't written well.
Is there anything that you might change about my code? Any critiques will be helpful. I learned and put this together in about 10 hours. (I'm really enjoying this!)
A future goal I have is to make this functionality web-accessible so that my friends can use it without downloading executable code.
from pydub import AudioSegment
from mutagen.mp3 import MP3
import random
import os
from glob import glob
from string import ascii_lowercase
from random import choice, randint, random
import sys
import time
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtCore
from PyQt5 import QtWidgets
class shredder(QWidget):
def __init__(self, parent = None):
super(shredder, self).__init__(parent)
self.setMinimumSize(350, 100)
#self.setFixedWidth(350)
#self.setFixedHeight(100)
layout = QVBoxLayout()
self.btn = QPushButton("Load MP3")
self.btn.clicked.connect(self.getfile)
layout.addWidget(self.btn)
self.le = QLabel("File Location:")
self.le.setAlignment(QtCore.Qt.AlignCenter)
layout.addWidget(self.le)
self.btn1 = QPushButton("Shred")
self.btn1.clicked.connect(self.shred)
layout.addWidget(self.btn1)
self.setLayout(layout)
self.setWindowTitle("MP3Shredder")
def getfile(self):
global filepath
filepath, _filter = QFileDialog.getOpenFileName(self, 'Open MP3 File',
'',"MP3 (*.mp3)")
if filepath:
self.le.setText("File Location: "+filepath)
def shred(self):
global filepath
try:
filepath
except NameError:
self.le.setText("You Must First Load A MP3 File To Shred!")
else:
#importing file with pydub from location by giving its path
song = AudioSegment.from_mp3(filepath)
#creates an MP3 object with mutagen from file location and saves it as variable
audio = MP3(filepath)
audio_info = audio.info
length = int(audio_info.length)
hours, mins, seconds = audio_duration(length)
print('Total Duration Of Song: {}:{}:{}'.format(hours, mins, seconds))
print("In Seconds: " + str(audio.info.length))
print("Creating " + str((audio.info.length//1)+1) +" shreds.")
os.makedirs(os.path.join(r"C:\mp3shredder"), exist_ok=True)
os.makedirs(os.path.join(r"C:\mp3shredder\temp"), exist_ok=True)
print("Shredding...")
#split sound in 1-second slices and export
for i, chunk in enumerate(song[::1000]):
with open(r"C:\mp3shredder\temp\piece%s.mp3" % i, "wb") as f:
chunk.export(f, format="mp3")
path = (r"C:\mp3shredder\temp")
files = os.listdir(path)
for index, file in enumerate(files):
os.rename(os.path.join(path, file), os.path.join(path, ''.join([choice(ascii_lowercase) for _ in range(randint(5, 8))])+".mp3"))
print("Shredding Complete!")
print("Gluing...")
shredded_pieces = [AudioSegment.from_mp3(mp3_file) for mp3_file in glob(r"C:\mp3shredder\temp\*.mp3")]
glue_it_back = AudioSegment.empty()
for song in shredded_pieces:
glue_it_back += song
filedir = os.path.dirname(filepath)
filename = os.path.basename(filepath)
glue_it_back.export(filedir + "/" + "SHREDDED_" + filename, format="mp3")
dir = (r"C:\mp3shredder\temp")
for f in os.listdir(dir):
os.remove(os.path.join(dir, f))
os.rmdir(dir)
print("Gluing Complete!")
print("Created: " + filedir + "/" + "SHREDDED_" + filename)
self.le.setText("Created: " + filedir + "/" + "SHREDDED_" + filename)
os.startfile(filedir)
# function to convert the information into
# some readable format
def audio_duration(length):
hours = length // 3600 # calculate in hours
length %= 3600
mins = length // 60 # calculate in minutes
length %= 60
seconds = length # calculate in seconds
return hours, mins, seconds # returns the duration
def main():
app = QApplication(sys.argv)
ex = shredder()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()