PYTHON PROGRAMMING NEED HELP ASAP
You will write an application to manage music collections -- a music collection is a list of albums.
The named tuples used for Albums and Songs are defined below, and an example of a music collection is given. (DO NOT HARDCODE THE VALUES FOR MUSIC!)
Album = namedtuple('Album', 'id artist title year songs') Song = namedtuple('Song', 'track title length play_count') MUSIC = [ Album("1", "Peter Gabriel", "Up", 2002, [Song(1, "Darkness", 411, 5), Song(2, "Growing Up", 453, 5)]), Album("2", "Simple Minds", "Once Upon a Time", 1985, [Song(1, "Once Upon a Time", 345, 9), Song(2, "All the Things She Said", 256, 10)]), Album("TRS", "The Rolling Stones", "Let It Bleed", 1969, [Song(1, "Gimme Shelter", 272, 3), Song(2, "Love In Vain", 259, 2), Song(3, "You Can't Always Get What You Want", 448, 10)]) ]
To achieve this, you need to:
Enter the song's track:
Enter the song's title:
Enter the song's length:
Enter the song's play_count:
Enter the album's id:
Enter the album's artist:
Enter the album's title:
Enter the album's year:
Enter the number of songs in this album:
Enter the song's track:
Enter the song's title:
Enter the song's length:
Enter the song's play_count:
Note that the last four lines should be repeated once for each song in the album.
Write a function called add_album that takes a music collection (a list of albums) as a parameter. The function should create a new album, add it to the end of the list, and then return the updated collection.
Write a function called remove_album that takes a music collection (a list of albums) and an ID as parameters. The function should remove the album that has a matching ID from the list, and then return the updated collection. If there is no album with a matching ID, simply print 'Album not found.' and return the collection.
Write a function called favorite_song that takes a music collection and an album ID as parameters. The function returns the song that is the "favorite" from the album that matched the ID. We'll define the favorite song as the one that has the highest playing time. (The playing time of a song is computed using its play_count and length.) If there is no album with a matching ID, return 'Album not found.'.
Write a function called unplayed_songs that takes a music collection and an album ID as parameters. It should return a list of the songs that have not been played from the album that matched the ID. If there is no album with a matching ID, simply print and return'Album not found.'.
Write a function called favorite_album that takes a music collection and returns the album that is the "favorite." We'll define the favorite album as the one that has the highest playing time. (An album's playing time is the sum of all its songs' playing time.)
Write a function called unplayed_albums that takes a music collection and returns a list of the albums that have not been played.
Write a function called print_menu that has no parameters. This function should display the menu (as shown below), and prompt the user for a choice. It should repeat the message 'Choose an option' while the user does not input a valid choice. The function should return the valid choice the user entered. Note that you only print the entire menu once per valid choice. That is, if the user enters an invalid choice, you should not repeat the entire menu, only the 'Choose an option' message.
MUSIC COLLECTION MANAGER
add - Add a new album
del - Remove an album
fav_a - Print favorite album
fav_s - Print favorite song
not_a - Print not played albums
not_s - Print not played songs
exit - Exit the application
Choose an option:
HINT: you can call get_song_input the desired amount of times to help create the list of songs for an album.
HINT: you can create extra functions to help you. For instance, a function that takes a song as a parameter and calculates its playing time could be helpful.
The program to manage music playlist
import datetime
import urllib
import urllib2
import os
import sys
import string
import tarfile
from threading import Thread as Process
#from multiprocessing import Process
from time import sleep
from random import randint
try:
import traceback
import requests
except ImportError:
pass
#####################################################
#connUser = False
threadUse = False
stop = False
skip = False
pause = False
play = False
debug = False
option = "n"
select = 0
current = ""
amount = 0
played = []
playlist = []
check = ""
width = 800
height = 600
console = False
text = ''
songNum = 1
kill = False
######################################################
try:
if len(sys.argv) > 1:
i = 1
while i <
len(sys.argv):
arg = sys.argv[i]
if arg == "--console":
console = True
elif arg == "-v":
debug = True
elif arg == "-c":
console = True
elif arg == "--verbose":
debug = True
elif arg == "-h" or arg == "--help":
print 'Plays music in the "Music" folder within the current
directory\n'
print "Usage: " + sys.argv[0] + " [options]"
print "Options: "
print "\t -h, --help\t Displays this help text"
print "\t -v, --verbose\t Displays extra information"
print "\t -c, --console\t Disables Pygame screen (text-only)"
kill = True
else:
print 'Ignoring bad option: ' + arg
i = i + 1
except:
pass
if kill:
exit()
######################################################
#
############
print "Starting Python Music Player " + version + "." + revision
#
#
############
######################################################
def mkdir(directory):
if not os.path.exists(directory):
os.makedirs(directory)
######################################################
def touch(path):
with open(path, 'a'):
os.utime(path,
None)
######################################################
# The shutdown process
def shutdown():
try:
bcast("\n")
bcast("Stopping...")
pygame.mixer.music.stop()
"""
try:
conn.close()
s.close()
except:
LogErr()
pass
"""
log("Shutdown
success")
log_file.close()
pygame.quit()
quit()
except:
log("An error
occoured")
LogErr()
log_file.close()
pygame.quit()
quit()
######################################################
# Custom logging function
def log(string):
try:
if debug:
print "[Debug]: " + string
log_file.write("[Logger]: ")
log_file.write(string)
log_file.write("\n")
except:
pass
######################################################
def LogErr():
try:
exc_type, exc_value,
exc_traceback = sys.exc_info()
lines =
traceback.format_exception(exc_type, exc_value,
exc_traceback)
log('')
log(''.join(line for
line in lines))
if debug:
bcast("[Error]: " + ''.join(line for line in lines), True)
except:
pass
######################################################
def bcast(string, err=False):
try:
if err:
print string
else:
print "[Player]: " + string
#conn.send(string)
text = string
#display(string,
background, screen)
except:
pass
######################################################
def updater():
log('Update requested; attempting...')
if update == 0:
bcast('No update
found.')
log('No update
found')
else:
bcast('Attempting to
retrive tarball...')
try:
log('Connecting to ' + url +'...')
try:
r = requests.get('http://' + url)
status = r.status_code
except:
status = 200
LogErr()
if status == int(200):
try:
filename = urllib.urlretrieve('http://' + url +
'/python/downloads/player/music-player-' + str(ver) + '.tar.gz',
'music-player-' + str(ver) + '.tar.gz')
except:
LogErr()
raise IOError
bcast('Installing...')
log('Download success')
log('Will now attempt to install update')
try:
mkdir('update')
os.rename("music-player-" + str(ver) + ".tar.gz",
'update/update.tar.gz')
os.chdir('update')
tar = tarfile.open("update.tar.gz")
tar.extractall()
tar.close()
os.remove('update.tar.gz')
os.chdir('..')
log('Success!')
bcast('Done!')
bcast("Move 'player.py' from the folder 'update' to: " +
os.path.dirname(os.getcwd()))
except:
LogErr()
bcast('Installation failed')
else:
bcast('Server is down')
raise IOError
except:
LogErr()
bcast('Download failed')
######################################################
# To control the player remotely (non-functional)
def server():
try:
import socket
HOST =
socket.gethostname()
PORT = 9000
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
except socket.error as
msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' +
msg[1]
LogErr()
try:
s.close()
except:
LogErr()
pass
s.listen(2)
print 'Started control
server on ' + HOST + ':' + str(PORT)
except:
print "Couldn't create
control server"
LogErr()
######################################################
# Get news updates
def news():
log("Getting news")
try:
news =
urllib2.urlopen("http://" + url + "/news.txt")
news = news.read()
if news == '':
bcast("No News")
log("No News")
else:
bcast(news)
log(news)
except:
LogErr()
bcast("Couldn't get news
updates", True)
######################################################
def control():
threadUse = True
option = ''
option = raw_input('> ')
try:
option =
option.replace("\n", '')
option =
option.lower()
if option == 'quit' or
option == 'stop':
print "Use Control-C to quit"
#stop = True
#shutdown()
elif option ==
'skip':
#skip = True
pygame.mixer.music.stop()
elif option ==
'update':
#update = True
updater()
# Play/Pause indev
elif option ==
'pause':
#pause = True
pygame.mixer.music.pause()
bcast('Paused')
elif option ==
'play':
#play = True
pygame.mixer.music.play()
elif option == '':
option = ''
elif option ==
'debug':
if debug == True:
print "Debug mode disabled"
debug = False
elif debug == False:
print "Debug mode enabled"
debug = True
elif option ==
"news":
news()
else:
bcast("Invalid command: " + option)
except:
LogErr()
sleep(0.1)
threadUse = False
###################################################
def control2():
try:
for event in
pygame.event.get():
if event.type == pygame.KEYDOWN:
if event == pygame.K_d:
print "Debug"
if debug:
debug = False
else:
debug = True
if event.key == pygame.K_SPACE or event.key == pygame.K_F11:
bcast("Pause")
if pause == True:
pygame.mixer.music.play()
pause = False
elif pause == False:
pygame.mixer.music.pause()
pause = True
if event.key == pygame.K_u:
bcast("Update")
updater()
if event.key == pygame.K_F12:
bcast("Skip")
pygame.mixer.music.stop()
if event.key == pygame.K_F10:
bcast("Quit")
shutdown()
except:
LogErr()
sleep(0.2)
######################################################
"""
def text_objects(text, font):
textSurface = font.render(text, True,
black)
return textSurface, textSurface.get_rect()
######################################################
def display(text):
screen.fill((225, 225, 225))
largeText =
pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text,
largeText)
TextRect.center = ((width/2),(height/2))
screen.blit(TextSurf, TextRect)
pygame.display.update()
pygame.display.flip()
"""
def display(text, background, screen):
font = pygame.font.Font("freesansbold",
36)
out = font.render(text, 1, (10, 10, 10))
textpos = out.get_rect()
textpos.centerx =
background.get_rect().centerx
background.blit(out, textpos)
# Blit everything to the screen
screen.blit(background, (0, 0))
pygame.display.flip()
######################################################
#server()
######################################################
mkdir('logs')
time = datetime.datetime.now()
try:
log_file = open("./logs/" + str(time),
"w+")
except:
LogErr()
bcast("Failed to create log")
######################################################
# Checking for updates...
""" Yep, that's an IP address"""
url = "50.177.194.52:8080"
update = 0
try:
log('Checking for updates...')
log('Getting info from ' + url)
ver = urllib2.urlopen('http://' + url +
'/version.txt')
rev = urllib2.urlopen('http://' + url +
'/rev.txt')
ver = ver.read()
rev = rev.read()
if float(ver) > float(version):
log('Update
found!')
bcast("Python Music
Player " + ver + " is availible")
bcast("Type update at
the prompt to download")
update = 1
elif float(ver) < float(version):
log('Indev vesion in
use')
bcast('Indev version in
use')
elif int(rev) > int(revision) and float(ver)
== float(version):
log('New revision
found!')
bcast('Revision ' +
str(rev) + ' is availible')
bcast('Type update at
the prompt to download')
update = 1
elif float(ver) == float(version):
log('No update
found')
bcast('No update
found')
except:
bcast('Failed to check for updates', True)
LogErr()
log('Update check failed')
######################################################
mkdir('Music')
log("Player starting...")
news()
######################################################
# Looking for pygame...
try:
import pygame
from pygame.locals import *
#import Screen
except ImportError:
LogErr()
try:
print "Downloading
assets"
log('Pygame missing;
getting installer')
osv = sys.platform
if osv == 'win32':
urllib.urlretrieve('https://pygame.org/ftp/pygame-1.9.1.win32-py2.7.msi',
'pygame-1.9.1.msi')
elif osv ==
'darwin':
urllib.urlretrieve('https://pygame.org/ftp/pygame-1.9.1release-python.org-32bit-py2.7-macosx10.3.dmg',
'pygame-mac.dmg')
log('Success!')
elif osv == 'linux2' or
'cygwin':
print 'You are using linux or cygwin'
print "Use the command 'sudo pip install pygame' to download\nthe
nessasary modules"
log(osv + ' detected; pip installer recommended')
else:
print 'Unrecognized os: ' + osv
try:
urllib.urlretrieve('http://' + url + '/pygame.tar.gz',
'pygame.tar.gz')
tar = tarfile.open("pygame.tar.gz")
tar.extractall()
tar.close()
os.remove('pygame.tar.gz')
except:
LogErr()
print "Failed to get assets"
exit()
print 'Please run the
installer that has been dropped into the ' +
os.path.dirname(os.getcwd()) + ' folder'
except:
print 'Failed to get
assets'
print "Please install
the 'pygame' module manually at pygame.org"
LogErr()
shutdown()
exit()
#######################################################
# Load pygame module
try:
pygame.init()
#pygame.font.init()
log('Pygame initialized')
except:
bcast("Couldn't run pygame.init()", True)
log("pygame.init() failed")
LogErr()
#######################################################
try:
if console == False:
screen =
pygame.display.set_mode((1000, 200))
pygame.display.set_caption("Music Player")
background =
pygame.Surface(screen.get_size())
background =
background.convert()
background.fill((250,
250, 250))
except:
bcast("Display error, console mode active",
True)
log("Display error")
LogErr()
console = True
log("Player started")
# Check the Music folder for tracks
sound_data = os.listdir('./Music')
try:
for i in sound_data:
playlist.append(i)
i = 0
amount = len(playlist)
log(str(amount) + " Songs found")
if amount == 0:
bcast('No music
found!')
shutdown()
bcast("Number of songs: " + str(amount))
#######################################################
# Play the music
while i != amount:
select = randint(0,
amount - 1)
if option.lower() ==
"y":
for i in song:
current = i
option = "n"
else:
current = playlist[select]
#current =
current.replace("\n", "")
if current not in
played:
# Try to load the track
bcast("Now Playing: " + current + " (" + str(songNum) + " out of "
+ str(amount) + ")")
log("Song " + str(songNum) + " out of " + str(amount))
try:
pygame.mixer.music.load("./Music/" + current)
log('Now Playing: ' + current)
except:
bcast("Couldn't play " + current)
#######################################################
# Play loaded track
pygame.mixer.music.play()
# Take user input for controlling player
while pygame.mixer.music.get_busy():
if console == False:
font = pygame.font.Font(None, 36)
out = font.render(text, 1, (10, 10, 10))
textpos = out.get_rect()
textpos.centerx = background.get_rect().centerx
screen.blit(background, (0, 0))
pygame.display.flip()
control2()
else:
t = Process(None, control())
t.daemon = False
t.start()
#######################################################
if not current in played:
played.append(current)
i = i + 1
sleep(0.2)
songNum = songNum + 1
bcast("All songs have been played!")
log('All songs have been played')
shutdown()
#######################################################
except:
LogErr()
shutdown()
PYTHON PROGRAMMING NEED HELP ASAP You will write an application to manage music collections -- a music collection is a l...
Many of us have large digital music collections that are not
always very well organized. It would be nice to have a program that
would manipulate our music collection based on attributes such as
artist, album title, song title, genre, song length, number times
played, and rating. For this assignment you will write a basic
digital music manager (DMM). Your DMM program must have a
text-based interface which allows the user to select from a main
menu of options including:...
Overview: You will be writing classes that implement a playlist simulation for a music streaming app.The Playlist class will contain a dynamic array of Song objects, and the Song class contains several pieces of information about a song. You will need to: 1) Finish the writing of two classes: Song and Playlist. The full header file for the Song class has been provided in a file called Song.h. 2) Write a main program (filename menu.cpp) that creates a single Playlist...
Problem 2 Using the Album and Music StoreDemo from problem 1, write a method to find all of the albums that are cheaper than a specific price In the MusicStoreDemo, add a new method called getAlbumsCheaperThan. The method passes in the ArrayList of albums and the price. The method will return an ArrayList of all albums cheaper than the price passed in. Update the main method in the Music Store Demo and have it find all of the albums that...
Please write this program in C++, thanks
Task 9.3 Write a complete C++ program to create a music player Your program should read in several album names, each album has up to 5 tracks as well as a genre. First declare genre for the album as an enumeration with at least three entries. Then declare an album structure that has five elements to hold the album name, genre, number of tracks, name of those tracks and track location. You can...
Program: Playlist (C++) I'm having difficulty figuring out how to get the header file to work. You will be building a linked list. Make sure to keep track of both the head and tail nodes. (1) Create three files to submit. Playlist.h - Class declaration Playlist.cpp - Class definition main.cpp - main() function Build the PlaylistNode class per the following specifications. Note: Some functions can initially be function stubs (empty functions), to be completed in later steps. Default constructor (1...
Ch 8 Program: Playlist (Java)You will be building a linked list. Make sure to keep track of both the head and tail nodes.(1) Create two files to submit.SongEntry.java - Class declarationPlaylist.java - Contains main() methodBuild the SongEntry class per the following specifications. Note: Some methods can initially be method stubs (empty methods), to be completed in later steps.Private fieldsString uniqueID - Initialized to "none" in default constructorstring songName - Initialized to "none" in default constructorstring artistName - Initialized to "none"...
Hi I've a problem with this code. When I add more than 1 song to the list, it doesn't show the first one, only shows the latest one, when I called the function displaysong, let's say when you add 2 songs ID 1 then ID 2, it shows only ID 1. Can you fix it. Everything else is fine.. #include <iostream> #include<string> using namespace std; //class Song class Song{ private: int songID; string title; string artist; string album; int year; public:...
Please use C programming to write the code to solve the following problem. Also, please use the instructions, functions, syntax and any other required part of the problem. Thanks in advance. Use these functions below especially: void inputStringFromUser(char *prompt, char *s, int arraySize); void songNameDuplicate(char *songName); void songNameFound(char *songName); void songNameNotFound(char *songName); void songNameDeleted(char *songName); void artistFound(char *artist); void artistNotFound(char *artist); void printMusicLibraryEmpty(void); void printMusicLibraryTitle(void); const int MAX_LENGTH = 1024; You will write a program that maintains information about your...
Write a C++ Program. you were required to first create a function called average. The return type is double and it takes in two parameters, one of type string the other of type double. In the average function write a for loop that PROMPT THE USER to enter in a grade 5 times, keep a sum of all the different grades then return the average of the grades. (sum / 5) Next write a function of type double called lowest...
please help with the marked ones the programming
language is python
code. 23.16 Write an RGB class that represents an RGB color. Store the red, green. and blue components. Include a _str_0 method and a luminance method that returns the luminance of the color. Write a main() function to test your code. 23.17 Write a CD class that represents a single music cd. Store the artist, title, genre, year of release, and playing time in minutes and seconds. However, instead...