Creating Web Based Music Player System Using MVC and AngularJs

Image
Image Link to YouTube video.

Introduction

In this article, we will learn how to create a simple web based music player system using MVC, AngularJS and Web API.

What is SHANU Music Player?

SHANU Music Player is a web-based music player system. User can upload their songs and play the selected albums. SHANU Music Player has two modules

1) Play Music
2) Album/Music CRUD (Upload and Manage Songs).

Shanu Music Player: This is the main module; users can play their favorite uploaded music from this page. First, by default, we will display the albums with album name and image. User can click on any of their favorite albums to play the music. When user clicks on the album image, we will play the first song of that album, by default. Users can add any number of songs to their albums to play.


Image
After the user selects the album, we will check for the songs to be added in the album. If there are no songs for the selected album, then we display the message as "No Songs has been added in this Album”. If album has songs, then we display our Shanu Music Player. From this page, the user can change and play any songs from the list as per his/her choice. In the player, we will display the album image and the title along with the current playing song file name. In the list, we will also display singer name, music file name,  and description of the file. User can play, pause, and play next and previous songs of the list

list

Album/Music CRUD (Upload and Manage Songs)

Upload and Manage Songs

In this module, we will manage album and music information. User can add albums with images and song details and upload songs in the album.

Manage Album Details

Manage Album Details

Here, user can add album details with image. Albums are nothing but it’s a favorite or play list. First, user can create albums and add all his/her favorite songs in that album. In the database, we have created two tables. One is Album table (as master) and another is music table (as details).

Music CRUD

Music CRUD

This is our main part as we will be adding all our music files to be played in this detail table. Here, we select our album from combobox and add music details and upload to our root directory to play our songs. Users can add new songs, edit, and delete the songs. We will see more detail in code part.

Prerequisites

  • Visual Studio 2015: You can download it from here.

Code part

  1. Create Database and Table.

    The following is the script to create a database, table, and sample insert query. Run this script in your SQL Server. I have used SQL Server 2014.
    1. -- =============================================   
    2. -- Author : Shanu   
    3. -- Create date : 2016-02-28   
    4. -- Description : To Create Database   
    5.   
    6. -- =============================================   
    7. --Script to create DB,Table and sample Insert data   
    8.   
    9. USE MASTER;   
    10.   
    11. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB   
    12. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'musicPlayerDB' )   
    13. BEGIN   
    14. ALTER DATABASE musicPlayerDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE   
    15. DROP DATABASE musicPlayerDB ;   
    16. END   
    17.   
    18.   
    19. CREATE DATABASE musicPlayerDB   
    20. GO   
    21.   
    22. USE musicPlayerDB   
    23. GO   
    24.   
    25. IF EXISTS ( SELECT [nameFROM sys.tables WHERE [name] = 'AlbumMaster' )   
    26. DROP TABLE AlbumMaster   
    27. GO   
    28.   
    29. CREATE TABLE AlbumMaster   
    30. (   
    31. AlbumID int identity(1,1),   
    32. AlbumName VARCHAR(200) NOT NULL ,   
    33. ImageName VARCHAR(500) NOT NULL   
    34. CONSTRAINT [PK_AlbumMaster] PRIMARY KEY CLUSTERED   
    35. (   
    36. [AlbumID] ASC   
    37.   
    38. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]   
    39. ON [PRIMARY]   
    40.   
    41. Insert into AlbumMaster(AlbumName,ImageName) Values('RedAlbum','RedAlbum.jpg')  
    42.   
    43. select * from AlbumMaster   
    44.   
    45.   
    46. IF EXISTS ( SELECT [nameFROM sys.tables WHERE [name] = 'MusicPlayerMaster' )   
    47. DROP TABLE MusicPlayerMaster   
    48. GO   
    49.   
    50. CREATE TABLE MusicPlayerMaster   
    51. (   
    52. MusicID int identity(1,1),   
    53. SingerName VARCHAR(100) NOT NULL ,   
    54. AlbumName VARCHAR(200) NOT NULL ,   
    55. MusicFileName VARCHAR(500) NOT NULL,   
    56. Description VARCHAR(100) NOT NULL,   
    57.   
    58. CONSTRAINT [PK_MusicPlayerMaster] PRIMARY KEY CLUSTERED   
    59. (   
    60. [MusicID] ASC   
    61.   
    62. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]   
    63. ON [PRIMARY]   
    64.   
    65. select * from MusicPlayerMaster   
    Stored Procedure : Run all this procedure one by one in your SQL Server,

    • SP to select all records of Album Details
      1. USE musicPlayerDB   
      2. GO   
      3.   
      4. -- =============================================   
      5. -- To Select Albumdetails   
      6. -- EXEC USP_AlbumMaster_Select ''   
      7. -- =============================================   
      8. CREATE PROCEDURE [dbo].[USP_AlbumMaster_Select]   
      9. (   
      10. @AlbumName VARCHAR(100) = ''   
      11. )   
      12. AS   
      13. BEGIN   
      14. SELECT AlbumID,AlbumName , ImageName  
      15. FROM AlbumMaster   
      16. WHERE   
      17. AlbumName like @AlbumName +'%'   
      18. Order By AlbumName  
      19. END   
    • SP to Insert Album Details.
      1. USE musicPlayerDB   
      2. GO   
      3.   
      4. -- To insert  
      5. -- EXEC [USP_Album_Insert] ''   
      6. -- =============================================   
      7. CREATE PROCEDURE [dbo].[USP_Album_Insert]   
      8. (   
      9. @AlbumName VARCHAR(200) = '',   
      10. @ImageName VARCHAR(500) = ''  
      11. )   
      12. AS   
      13. BEGIN   
      14. IF NOT EXISTS (SELECT * FROM AlbumMaster WHERE AlbumName=@AlbumName)   
      15. BEGIN   
      16.   
      17. INSERT INTO [dbo].AlbumMaster (AlbumName ,ImageName )  
      18. VALUES (@AlbumName ,@ImageName )  
      19.   
      20. Select 'Inserted' as results   
      21.   
      22. END   
      23. ELSE   
      24. BEGIN   
      25. Select 'Exists' as results   
      26. END   
      27.   
      28. END   
    • SP to select all records of Music details
      1. USE musicPlayerDB   
      2. GO   
      3. -- 1) select all MusicPlayerMaster records   
      4.   
      5. -- Author : Shanu   
      6. -- Create date : 2016-08-23   
      7. -- Description :select top 10 random kidsLearnerMaster records   
      8. -- Tables used : MusicPlayerMaster   
      9. -- Modifier : Shanu   
      10. -- Modify date : 2016-08-23   
      11. -- =============================================   
      12. -- To Select all user roles   
      13. -- EXEC USP_MusicAlbum_SelectALL ''   
      14. -- =============================================   
      15. CREATE PROCEDURE [dbo].[USP_MusicAlbum_SelectALL]   
      16. (   
      17. @AlbumName VARCHAR(100) = ''   
      18. )   
      19. AS   
      20. BEGIN   
      21. SELECT MusicID,   
      22. SingerName ,   
      23. AlbumName ,   
      24. MusicFileName,   
      25. Description   
      26. FROM MusicPlayerMaster   
      27. WHERE   
      28. AlbumName like @AlbumName +'%'   
      29.   
      30. END  
    • SP to Insert Music Details
      1. USE musicPlayerDB  
      2. GO   
      3.   
      4. Insert MusicPlayerMaster records   
      5.   
      6. -- Author : Shanu   
      7. -- Create date : 2016-08-23   
      8. -- Description :Insert   
      9. -- Tables used : MusicPlayerMaster   
      10. -- Modifier : Shanu   
      11. -- Modify date : 2016-08-23   
      12. -- =============================================   
      13. -- To insert  
      14. -- EXEC USP_MusicAlbum_Insert ''   
      15. -- =============================================   
      16. CREATE PROCEDURE [dbo].[USP_MusicAlbum_Insert]   
      17. (   
      18. @SingerName VARCHAR(100) = '',   
      19. @AlbumName VARCHAR(200) = '',   
      20. @MusicFileName VARCHAR(500) = '',   
      21. @Description VARCHAR(100) = ''  
      22. )   
      23. AS   
      24. BEGIN   
      25. IF NOT EXISTS (SELECT * FROM MusicPlayerMaster WHERE MusicFileName=@MusicFileName)   
      26. BEGIN   
      27.   
      28. INSERT INTO [dbo].[MusicPlayerMaster]  
      29. (SingerName ,AlbumName ,MusicFileName ,Description)  
      30. VALUES  
      31. (@SingerName ,@AlbumName ,@MusicFileName ,@Description)  
      32.   
      33. Select 'Inserted' as results   
      34.   
      35. END   
      36. ELSE   
      37. BEGIN   
      38. Select 'Exists' as results   
      39. END   
      40.   
      41. END   
    • SP to Update Music Details
      1. USE musicPlayerDB   
      2. GO   
      3. Update all MusicPlayerMaster records   
      4.   
      5. -- Author : Shanu   
      6. -- Create date : 2016-08-23   
      7. -- Description :Update   
      8. -- Tables used : MusicPlayerMaster   
      9. -- Modifier : Shanu   
      10. -- Modify date : 2016-08-23   
      11. -- =============================================   
      12. -- To Select all user roles   
      13. -- EXEC USP_MusicAlbum_Update ''   
      14. -- =============================================   
      15. Create PROCEDURE [dbo].[USP_MusicAlbum_Update]   
      16. (   
      17. @musicID VARCHAR(20) = '',   
      18. @SingerName VARCHAR(100) = '',   
      19. @AlbumName VARCHAR(200) = '',   
      20. @MusicFileName VARCHAR(500) = '',   
      21. @Description VARCHAR(100) = ''  
      22. )   
      23. AS   
      24. BEGIN   
      25. UPDATE [dbo].[MusicPlayerMaster]  
      26. SET [SingerName] = @SingerName,  
      27. [AlbumName] = @AlbumName,  
      28. [MusicFileName] = @MusicFileName,  
      29. [Description] = @Description   
      30. WHERE   
      31. musicID = @musicID   
      32. Select 'Updated' as results   
      33. END  
    • SP to Delete record by Admin
      1.  USE musicPlayerDB  
      2. GO  
      3. -- 5) Stored procedure To Delete  KIDSLEARN   
      4.   
      5. -- Author      : Shanu                                                                  
      6. -- Create date : 2016-02-28                                                                 
      7. -- Description :To Delete KIDSLEARN detail                                            
      8. -- Tables used :  kidsLearnerMaster                                                              
      9. -- Modifier    : Shanu                                                                  
      10. -- Modify date : 2016-02-28                                                                  
      11. -- =============================================    
      12. -- To delete KIDSLEARN record  
      13. -- =============================================                                                            
      14. Create PROCEDURE [dbo].[USP_KIDSLEARN_Delete]                                                
      15.    ( @KIDIDENTITY       VARCHAR(20)     = '' )                                                          
      16. AS                                                                  
      17. BEGIN         
      18.         DELETE FROM kidsLearnerMaster WHERE KIDIDENTITY=@KIDIDENTITY                  
      19.               
      20. END  
  2. Create your MVC Web Application in Visual Studio 2015

    After installing the Visual Studio 2015, click Start >> Programs >> select Visual Studio 2015 >> Click Visual Studio 2015. Click New >> Project >> select Web >> ASP.NET Web Application. Enter your project name and click OK.

    MVC Web Application

    Select MVC,WEB API and click OK.

    MVC

    Web.Config : To upload large file size

    Note: Here, we need to upload music files as mp3 or wav. So, we need to upload large files to our root directory. For uploading large files in webconfig, we add the below code part,
    1. <system.web>  
    2. <httpRuntime   executionTimeout="3600" maxRequestLength="102400" />   
    3.   </system.web>  
    4.   
    5. <system.webServer>  
    6. <security>  
    7.         <requestFiltering>  
    8.             <requestLimits maxAllowedContentLength="104857600" />  
    9.         </requestFiltering>  
    10.     </security>  
    11.   </system.webServer>  

Add Database using ADO.NET Entity Data Model

Right click the project and click Add, then New Item. Select Data, then ADO.NET Entity Data Model and give the name for your EF and click Add.

Add Database

Select "EF Designer from database" and click Next.

EF Designer from database

Connect to your database. Click Next to select Tables and Stored Procedure for Menu management.

Connect

Now, select all your tables and Stored procedure details and click Finish.

tables and Stored procedure details

Procedure to add Web API Controller

Right-click the Controllers folder. Click Add and then click Controller.

Select Web API 2 Controller – Empty, click add and give name for your Web API controller.

Working with WEBAPI Controller for CRUD

Select Controller and add an Empty Web API 2 Controller. Provide your name to the Web API controller and click OK. Here, for our Web API Controller, we have given the name “MusicAPIController".

As we have created Web API controller, we can see that our controller has been inherited with ApiController. As we all know, Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles.

Web API has the following four methods as Get/Post/Put and Delete where:

  • Get is to request for the data. (Select)
  • Post is to create a data. (Insert)
  • Put is to update the data.
  • Delete is to delete data.

Get Method

In our example, I have used only one Get method since I am using only one Stored Procedure. We need to create an object for our Entity and write our Get method to do Select/Insert/Update and Delete operations.

Select Operation


We use a Get method to get all the details of the both AlbumMaster and MusicDetail tables using an entity object and we return the result as IEnumerable. We use this method in our AngularJS and display the result in an MVC page from the AngularJS controller. Using Ng-Repeat, we can bind the details.

Here, we can see in the getAlbums method I have passed the search parameter to the USP_AlbumMaster_Select ALL Stored Procedure. In the Stored Procedure, I used like "%" to return all the records if the search parameter is empty.

  1. // To select Album Details  
  2.        [HttpGet]  
  3.        public IEnumerable<USP_AlbumMaster_Select_Result> getAlbums(string AlbumName)  
  4.        {  
  5.            if (AlbumName == null)  
  6.                AlbumName = "";  
  7.            return objapi.USP_AlbumMaster_Select(AlbumName).AsEnumerable();  
  8.        }  
Insert Operation

The same as select, we passed all the parameters to the insert procedure. This insert method will return the result from the database as a record is inserted or not. We will get the result and display it from the AngularJS Controller to MVC application.
  1. [HttpGet]  
  2.         public IEnumerable<string> insertAlbum(string AlbumName, string ImageName)  
  3.         {  
  4.             if (AlbumName == null)  
  5.                 AlbumName = "";  
  6.   
  7.             if (ImageName == null)  
  8.                 ImageName = "";  
  9.   
  10.             return objapi.USP_Album_Insert(AlbumName, ImageName).AsEnumerable();  
  11.   
  12.         }  
Same like Album, we will be using the methods for Music Details to perform our CRUD operations here is the code for Select, Insert, Update and Delete.
  1. // to Search all Music Album Details  
  2. [HttpGet]  
  3. public IEnumerable<USP_MusicAlbum_SelectALL_Result> getMusicSelectALL(string AlbumName)  
  4. {  
  5.     if (AlbumName == null)  
  6.         AlbumName = "";  
  7.   
  8.     return objapi.USP_MusicAlbum_SelectALL(AlbumName).AsEnumerable();  
  9. }  
  10.   
  11. // To insert Music Details  
  12. [HttpGet]  
  13. public IEnumerable<string> insertMusic(string SingerName, string AlbumName, string MusicFileName, string Description)  
  14. {  
  15.     if (SingerName == null)  
  16.         SingerName = "";  
  17.   
  18.     if (MusicFileName == null)  
  19.         MusicFileName = "";  
  20.   
  21.     if (AlbumName == null)  
  22.         AlbumName = "";  
  23.   
  24.     if (Description == null)  
  25.         Description = "";  
  26.   
  27.     return objapi.USP_MusicAlbum_Insert(SingerName, AlbumName, MusicFileName, Description).AsEnumerable();  
  28.   
  29. }  
  30.   
  31. // To Update Music Details  
  32. [HttpGet]  
  33. public IEnumerable<string> updateMusic(string musicID, string SingerName, string AlbumName, string MusicFileName, string Description)  
  34. {  
  35.     if (musicID == null)  
  36.         musicID = "0";  
  37.   
  38.     if (SingerName == null)  
  39.         SingerName = "";  
  40.   
  41.     if (MusicFileName == null)  
  42.         MusicFileName = "";  
  43.   
  44.     if (AlbumName == null)  
  45.         AlbumName = "";  
  46.   
  47.     if (Description == null)  
  48.         Description = "";  
  49.   
  50.     return objapi.USP_MusicAlbum_Update(musicID, SingerName, AlbumName, MusicFileName, Description).AsEnumerable();  
  51.   
  52. }  
  53.   
  54.   
  55.   
  56. // To Delete Music Details  
  57. [HttpGet]  
  58. public IEnumerable<string> deleteMusic(string musicID)  
  59. {  
  60.     if (musicID == null)  
  61.         musicID = "0";  
  62.     return objapi.USP_MusicAlbum_Delete(musicID).AsEnumerable();  
  63.   
  64. }  
Next, we will create our AngularJs Controller and View page to perform our CRUD operations to manage both Albums and MusicDetails.

Album/Music CRUD (Upload and Manage Songs)

Upload and Manage Songs

Creating AngularJS Controller

Firstly, create a folder inside the Scripts folder and name it as “MyAngular”.

 Scripts folder

Now, add your Angular Controller inside the folder.

Right click the MyAngular folder and click Add and New Item. Select Web and then AngularJS Controller and provide a name for the Controller. I have named my AngularJS Controller “Controller.js”.

Controller

Once the AngularJS Controller is created, we can see by default the controller will have the code with the default module definition and all.

If the AngularJS package is missing, then add the package to your project. Right click your MVC project and click Manage NuGet Packages. Search for AngularJS and click Install.

Manage NuGet Packages
Procedure to Create AngularJS Script Files

Modules.js: Here, we will add the reference to the AngularJS JavaScript and create an Angular Module named “AngularJs_Module”.
  1. // <reference path="../angular.js" />    
  2. /// <reference path="../angular.min.js" />     
  3. /// <reference path="../angular-animate.js" />     
  4. /// <reference path="../angular-animate.min.js" />     
  5. var app;  
  6. (function () {  
  7.     app = angular.module("AngularJs_Module", ['ngAnimate']);  
  8. })();  
Controllers: In AngularJS Controller, I have done all the business logic and returned the data from Web API to our MVC HTML page. 
  1. Variable declarations

    Firstly, we declared all the local variables needed to be used.
    1. app.controller("AngularJs_Controller"function ($scope, $timeout, $rootScope, $window, $http , FileUploadService) {  
    2.     $scope.date = new Date();  
    3.     $scope.MyName = "shanu";  
    4.     // For Album Details  
    5.     $scope.AlbumIdentitys = 0;  
    6.     $scope.UImage = "";  
    7.     $scope.AlbumName = "";  
    8.   
    9.     // For Music Details  
    10.     $scope.musicID = 0;  
    11.     $scope.SingerName = "";  
    12.     $scope.AlbumNameS = "RedAlbum";  
    13.     $scope.MusicFileName = "";  
    14.     $scope.Description = "";  
    15.   
    16.     //For Visible design  
    17.   
    18.     $scope.showMusicsAdd = false;  
    19.     $scope.showAlbum = true;  
    20.     $scope.showMusics = false;  
    21.     $scope.showEditMusics = false;  
  2. Methods

    Select Method

    In the select method, we have used $http.get to get the details of both Album and Music Details from Web API. In the get method, we will provide our API Controller name and method to get the details.

    The final result will be displayed to the MVC HTML page using data-ng-repeat.
    1. // This method is to get all the kids Learn Details to display for CRUD.   
    2.     selectAlbumDetails($scope.AlbumName);  
    3.   
    4.     function selectAlbumDetails(AlbumName) {  
    5.         $http.get('/api/MusicAPI/getAlbums/', { params: { AlbumName: AlbumName } }).success(function (data) {  
    6.             $scope.AlbumData = data;  
    7.             
    8.             if ($scope.AlbumData.length > 0) {  
    9.             }  
    10.         })  
    11.    .error(function () {  
    12.        $scope.error = "An Error has occured while loading posts!";  
    13.    });  
    14.   
    15.         $http.get('/api/MusicAPI/getMusicSelectALL/', { params: { AlbumName: AlbumName } }).success(function (data) {  
    16.             $scope.MusicData = data;  
    17.   
    18.             if ($scope.AlbumData.length > 0) {  
    19.             }  
    20.         })  
    21.   .error(function () {  
    22.       $scope.error = "An Error has occured while loading posts!";  
    23.   });  
    24.     }  

Insert Album

For adding album, we also upload album image to our rood directory .

Note: First, create a folder named “uploads” from your solution to upload all your album images and music files like mp3.

Insert Album
Image Upload:. 

$scope.ChechFileValid

This method checks if the attached image file is valid or not. If the image file is not valid, then display the error message.

  1. $scope.SaveAlbum = function ()  
In this method, pass the image file to the UploadFile method and once the image is uploaded successfully to our root folder, the Album details will be inserted into database.

fac.UploadFile = function (file) In this method, using $http.post, we pass our image file to the MVC Controller and our HTTPost method as in the following,
  1. //Form Validation  
  2.     $scope.$watch("f1.$valid"function (isValid) {  
  3.         $scope.IsFormValid = isValid;  
  4.     });  
  5.   
  6.     //File Validation  
  7.     $scope.ChechFileValid = function (file) {  
  8.         var isValid = false;  
  9.         if ($scope.SelectedFileForUpload != null) {  
  10.             if ((file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') && file.size <= (800 * 800)) {  
  11.                 $scope.FileInvalidMessage = "";  
  12.                 isValid = true;  
  13.             }  
  14.             else {  
  15.                 $scope.FileInvalidMessage = "Only JPEG/PNG/Gif Image can be upload )";  
  16.             }  
  17.         }  
  18.         else {  
  19.             $scope.FileInvalidMessage = "Image required!";  
  20.         }  
  21.         $scope.IsFileValid = isValid;  
  22.     };  
  23.   
  24.     //File Select event   
  25.     $scope.selectFileforUpload = function (file) {  
  26.   
  27.         var files = file[0];  
  28.         $scope.Imagename = files.name;  
  29.         //    alert($scope.Imagename);  
  30.         $scope.SelectedFileForUpload = file[0];  
  31.   
  32.     }  
  33.   
  34.     //Save Album File  
  35.     $scope.saveAlbum = function () {  
  36.         $scope.IsFormSubmitted = true;  
  37.   
  38.         $scope.Message = "";  
  39.         $scope.ChechFileValid($scope.SelectedFileForUpload);  
  40.   
  41.         if ($scope.IsFormValid && $scope.IsFileValid) {  
  42.             FileUploadService.UploadFile($scope.SelectedFileForUpload).then(function (d) {  
  43.   
  44.                 $http.get('/api/MusicAPI/insertAlbum/', { params: { AlbumName: $scope.AlbumName, ImageName: $scope.Imagename } }).success(function (data) {  
  45.                     $scope.menuInserted = data;  
  46.                     alert($scope.menuInserted);  
  47.                     cleardetails();  
  48.                     selectAlbumDetails('');  
  49.                 })  
  50.          .error(function () {  
  51.              $scope.error = "An Error has occured while loading posts!";  
  52.          });  
  53.   
  54.             }, function (e) {  
  55.                 alert(e);  
  56.             });  
  57.         }  
  58.         else {  
  59.             $scope.Message = "All the fields are required.";  
  60.         }  
  61.   
  62.     };  
  63.   
  64.   
  65. .factory('FileUploadService'function ($http, $q) {  
  66.     
  67.     var fac = {};  
  68.     fac.UploadFile = function (file) {  
  69.         var formData = new FormData();  
  70.         formData.append("file", file);  
  71.   
  72.         var defer = $q.defer();  
  73.         $http.post("/KidslearnAdmin/UploadFile", formData,  
  74.             {  
  75.                 withCredentials: true,  
  76.                 headers: { 'Content-Type': undefined },  
  77.                 transformRequest: angular.identity  
  78.             })  
  79.         .success(function (d) {  
  80.             defer.resolve(d);  
  81.         })  
  82.         .error(function () {  
  83.             defer.reject("File Upload Failed!");  
  84.         });  
  85.   
  86.         return defer.promise;  
  87.   
  88.     }  
  89.     return fac;  
  90.   
  91.     //---------------------------------------------  
  92.     //End of Image Upload and Insert record  
This save part explains about our Album details save to our database using AngularJS Controller. Same like this, we will be saving and uploading our music files to our root directory to play our music.

Here is the AngularJS Controller code part to perform our Music Details CRUD operation and upload Music files to our root folder.
  1. // ********   Music CRUD Management and MP3 File Upload  
  2.   
  3.           
  4.     //Form Validation  
  5.     $scope.$watch("f2.$valid"function (isValid) {  
  6.         $scope.IsFormValid = isValid;  
  7.     });  
  8.   
  9.     // THIS IS REQUIRED AS File Control is not supported 2 way binding features of Angular  
  10.     // ------------------------------------------------------------------------------------  
  11.   
  12.   
  13.     //File Validation  
  14.     $scope.ChechMusicFileValid = function (file) {  
  15.         var isValid = false;  
  16.         if ($scope.selectmp3FileforUpload != null) {  
  17.             $scope.FileInvalidMessage = "";  
  18.             isValid = true;  
  19.         }  
  20.         else {  
  21.             $scope.FileInvalidMessage = "Music File required!";  
  22.         }  
  23.         $scope.IsFileValid = isValid;  
  24.     };  
  25.   
  26.     //to upload Music File  
  27.   
  28.     //File Select event   
  29.     $scope.selectmp3FileforUpload = function (file) {          
  30.         var files = file[0];         
  31.         $scope.MusicFileName = files.name;  
  32.         //    alert($scope.Imagename);  
  33.         $scope.selectmp3FileforUpload = file[0];  
  34.   
  35.     }  
  36.   
  37.   
  38.     //Save Music  File  
  39.     $scope.saveMusicDetails = function () {  
  40.           
  41.         $scope.IsFormSubmitted = true;  
  42.   
  43.         $scope.Message = "";  
  44.            
  45.   
  46.         $scope.ChechMusicFileValid($scope.selectmp3FileforUpload);  
  47.           
  48.   
  49.         if ($scope.IsFormValid && $scope.IsFileValid) {  
  50.             
  51.             FileUploadService.UploadFile($scope.selectmp3FileforUpload).then(function (d) {  
  52.                  
  53.                 //if the Music ID=0 means its new Music insert here i will call the Web api insert method  
  54.                 if ($scope.musicID == 0) {  
  55.   
  56.                     $http.get('/api/MusicAPI/insertMusic/', { params: { SingerName: $scope.SingerName, AlbumName: $scope.AlbumNameS, MusicFileName: $scope.MusicFileName, Description: $scope.Description } }).success(function (data) {  
  57.   
  58.                         $scope.menuInserted = data;  
  59.                         alert($scope.menuInserted);  
  60.   
  61.   
  62.                         cleardetails();  
  63.                         selectAlbumDetails('');  
  64.                     })  
  65.              .error(function () {  
  66.                  $scope.error = "An Error has occured while loading posts!";  
  67.              });  
  68.                 }  
  69.   
  70.   
  71.                 else {  // to update to the Music details  
  72.                     $http.get('/api/MusicAPI/updateMusic/', { params: { musicID: $scope.musicID, SingerName: $scope.SingerName, AlbumName: $scope.AlbumNameS, MusicFileName: $scope.MusicFileName, Description: $scope.Description } }).success(function (data) {  
  73.                         $scope.menuUpdated = data;  
  74.                         alert($scope.menuUpdated);  
  75.   
  76.                         cleardetails();  
  77.                         selectAlbumDetails('');  
  78.                     })  
  79.             .error(function () {  
  80.                 $scope.error = "An Error has occured while loading posts!";  
  81.             });  
  82.                 }  
  83.   
  84.             }, function (e) {  
  85.                 alert(e);  
  86.             });  
  87.         }  
  88.         else {  
  89.             $scope.Message = "All the fields are required.";  
  90.         }  
  91.   
  92.     };  
  93.   
  94.     //Edit MusicEdit  Details  
  95.     $scope.MusicEdit = function KidsEdit(musicID, SingerName, AlbumName, MusicFileName, Description) {  
  96.         cleardetails();  
  97.         $scope.showEditMusics = true;  
  98.         alert(musicID);  
  99.         $scope.musicID = musicID;  
  100.         $scope.SingerName = SingerName;  
  101.         $scope.AlbumNameS = AlbumName;  
  102.         $scope.MusicFileName = MusicFileName;  
  103.         $scope.Description = Description;  
  104.     }  
  105.   
  106.     //Delete MusicDelete Detail  
  107.     $scope.MusicDelete = function KidsDelete(musicIDs) {  
  108.         cleardetails();  
  109.         $scope.showEditMusics = true;  
  110.         $scope.musicID = musicIDs;  
  111.         var delConfirm = confirm("Are you sure you want to delete the Kids Lear Detail ?");  
  112.         if (delConfirm == true) {  
  113.   
  114.             $http.get('/api/MusicAPI/deleteMusic/', { params: { musicID: $scope.musicID } }).success(function (data) {  
  115.                 alert("Music Detail Deleted Successfully!!");  
  116.                 cleardetails();  
  117.                 selectAlbumDetails('');  
  118.             })  
  119.       .error(function () {  
  120.           $scope.error = "An Error has occured while loading posts!";  
  121.       });  
  122.   
  123.         }  
  124.     }  
  125.   
  126.   
  127.      
  128.     //----------------------------------------------------------------------------------------  
Music Player Module

This is our main module where user can play his/her favorite songs from this page. First, we will display all Album details with images in home page.

Music Player Module

Here, we have created one more AngularJS Controller and named it as HomeController. In this controller, we will get details of albums and music to play our songs.

Album display: First, we create a new AngularJS controller and declare all variables. In home page, we display all the album details with image and album title. By default, we call the selectAlbumDetails() method to display the album details in home page.
  1. // <reference path="../angular.js" />    
  2. /// <reference path="../angular.min.js" />     
  3. /// <reference path="../angular-animate.js" />     
  4. /// <reference path="../angular-animate.min.js" />     
  5. var app;  
  6. (function () {  
  7.     app = angular.module("AngularJsHome_Module", ['ngAnimate']);  
  8. })();  
  9.   
  10.   
  11. app.controller("AngularJsHome_Controller"function ($scope, $timeout, $rootScope, $window, $http) {  
  12.     $scope.date = new Date();  
  13.     $scope.MyName = "shanu";  
  14.     // For Album Details  
  15.     $scope.AlbumIdentitys = 0;  
  16.     $scope.AlbumImage = "RedAlbum.jpg";  
  17.     $scope.AlbumName = "RedAlbu";  
  18.   
  19.     // For Music Details  
  20.     $scope.musicID = 0;  
  21.     $scope.SingerName = "";  
  22.     $scope.AlbumNameS = "RedAlbum";  
  23.     $scope.MusicFileName = "";  
  24.     $scope.Description = "";  
  25.   
  26.     // Play Songs  
  27.     $scope.selectedSongIndex = 0;  
  28.     $scope.songsCount = 0;  
  29.     $scope.CurrentSong = "Alarm06NOK.wav";  
  30.     $scope.selectedSongstoPlay = "/uploads/Alarm06NOK.wav";  
  31.     //For Visible design  
  32.    
  33.     $scope.showAlbum = true;  
  34.     $scope.showMusics = false;  
  35.     $scope.showButton = false;  
  36.     $scope.showSounds = false;  
  37.     
  38.     // This method is to get all the kids Learn Details to display for CRUD.   
  39.     selectAlbumDetails('');  
  40.   
  41.     function selectAlbumDetails(AlbumName) {  
  42.         $http.get('/api/MusicAPI/getAlbums/', { params: { AlbumName: AlbumName } }).success(function (data) {  
  43.             $scope.AlbumData = data;  
  44.   
  45.             if ($scope.AlbumData.length > 0) {  
  46.             }  
  47.         })  
  48.    .error(function () {  
  49.        $scope.error = "An Error has occured while loading posts!";  
  50.    });  
  51.   
  52.         
  53.     }  
In home page, we display only 3 Album details in one row. To fix the 3 columns,  first in home page Index View page, we add this CSS style.
  1. .columns {  
  2.   columns: 3;  
  3. }  
In html part, we use this style in div tag to display 3 columns per row.
  1. <div class="columns">  
  2.                             <div ng-repeat="details in AlbumData">  
  3.                                 <table style='width: 99%;table-layout:fixed;'>  
  4.                                     <tr>  
  5.                                         <td align="center">  
  6.                                             <img src="~/uploads/{{details.ImageName}}" alt="{{details.ImageName}}" width="144px" height="144px" ng-click="showMusicAlbum(details.AlbumName, details.ImageName)" />  
  7.                                         </td>  
  8.                                     </tr>  
  9.                                     <tr>  
  10.                                         <td align="center">  
  11.                                             <span style="color:#257815;font-size:large"><b>{{details.AlbumName}}</b></span>  
  12.   
  13.                                         </td>  
  14.                                     </tr>  
  15.                                     <tr>  
  16.                                         <td>  
  17.   
  18.                                             <img src="~/Images/blank.gif" alt="" width="1" height="2" />  
  19.                                         </td>  
  20.                                     </tr>  
  21.                                 </table>  
  22.                             </div>  
  23.                         </div>  
Music Player

Music Player:

In Music player part, first we declare the audio tag in html part .In audio tag, we give the source audio file from our AngularJS controller part.
  1. <audio id="audioPlay">  
  2.                     <source  src="{{selectedSongstoPlay}}"></source>  
  3.                 </audio>  
To Play Songs

To play the songs, first we will be loading all the songs of the selected album. In this method, we pass our selected Album to our Web API to load all songs. If there is no records for the album, then we display the message as ("No Songs has been added in this Album" .If songs are available for the album, then we pick the first record of song and pass the song name to playMusic method.
  1. var audio = document.getElementById("audioPlay");  
  2.     //Show Music   Details  
  3.     $scope.showMusicAlbum = function showMusicAlbum(AlbumNames, ImageName) {  
  4.   
  5.         $scope.AlbumName = AlbumNames;  
  6.         $scope.AlbumImage = ImageName;  
  7.            
  8.         // Get the Music Play list by Albums  
  9.         $http.get('/api/MusicAPI/getMusicSelectALL/', { params: { AlbumName: $scope.AlbumName } }).success(function (data) {  
  10.             $scope.MusicData = data;  
  11.              
  12.             if ($scope.MusicData.length > 0) {  
  13.                 $scope.showAlbum = false;  
  14.                 $scope.showMusics = true;  
  15.                 $scope.showButton = true;  
  16.                 $scope.songsCount=$scope.MusicData.length;  
  17.                 $scope.selectedSongIndex = 0;  
  18.                 $scope.CurrentSong = $scope.MusicData[$scope.selectedSongIndex].MusicFileName;  
  19.                 $scope.playMusic($scope.selectedSongIndex, $scope.CurrentSong);  
  20.             }  
  21.             else  
  22.             {  
  23.                 alert("No Songs has been added in this Album")  
  24.                 $scope.songsCount = 0;  
  25.                 $scope.selectedSongIndex = 0;  
  26.             }  
  27.              
  28.         })  
  29. .error(function () {  
  30.     $scope.error = "An Error has occured while loading posts!";  
  31. });  
  32.     }  
In playMusic, we get the music file name and play the current selected songs.
  1. //Play Songs  
  2.     $scope.playMusic = function (indexnumber, musicFileName) {  
  3.         $scope.selectedSongIndex = indexnumber;  
  4.         $scope.CurrentSong = musicFileName;  
  5.     $scope.selectedSongstoPlay = "/uploads/" + musicFileName;       
  6.     
  7.         audio.load();  
  8.         audio.play();  
  9.   
  10.         audio.addEventListener('ended'function () {  
  11.             if ($scope.selectedSongIndex < $scope.songsCount) {  
  12.                 $scope.selectedSongIndex = $scope.selectedSongIndex + 1;  
  13.             }  
  14.             else {  
  15.                 $scope.selectedSongIndex = 0;  
  16.             }  
  17.   
  18.             $scope.CurrentSong = $scope.MusicData[$scope.selectedSongIndex].MusicFileName;  
  19.             $scope.selectedSongstoPlay = "/uploads/" + musicFileName;  
  20.   
  21.             audio.load();  
  22.             audio.play();  
  23.              
  24.         });  
  25.     }  

play

Play Next Song

In Next image click, we call the nextSong method .In this method,  we check and increment the selected song index to play the next song .We will pass the song name to playMusic method to play the song.
  1. //next Song Play  
  2.     $scope.nextSong = function () {  
  3.         if ($scope.selectedSongIndex < $scope.songsCount) {  
  4.             $scope.selectedSongIndex = $scope.selectedSongIndex + 1;  
  5.         }  
  6.         else {  
  7.             $scope.selectedSongIndex = 0;  
  8.         }  
  9.   
  10.         $scope.CurrentSong = $scope.MusicData[$scope.selectedSongIndex].MusicFileName;  
  11.         $scope.playMusic($scope.selectedSongIndex, $scope.CurrentSong);  
  12.     }  
Play Previous Song 

In Previous image click, we call the previousSong method .In this method, we check and decrement the selected song index to play the previous song .We will pass the song name to playMusic method to play the song.
  1. //Previous Song Play  
  2.     $scope.previousSong = function ()  
  3.     {  
  4.         if($scope.selectedSongIndex>0)  
  5.         {  
  6.             $scope.selectedSongIndex = $scope.selectedSongIndex - 1;  
  7.         }  
  8.         else  
  9.         {  
  10.             $scope.selectedSongIndex = 0;  
  11.         }  
  12.   
  13.         $scope.CurrentSong = $scope.MusicData[$scope.selectedSongIndex].MusicFileName;  
  14.         $scope.playMusic($scope.selectedSongIndex, $scope.CurrentSong);  
  15.     } 
Pause Current Song

In stop image click, we call the pauseMusic method .In this method, we pause the currently playing song.
  1. //Pause Songs  
  2.    $scope.pauseMusic = function () {  
  3.        audio.pause();  
  4.    }  
Play Current Song 

In play image click, we call the playCurrent method .In this method we continue playing of paused song.
  1. //play Current Songs  
  2.     $scope.playCurrent = function () {        
  3.         audio.play();  
  4.     }  
Conclusion

Hope you all like this Shanu Music Player web based system.

This is simple web based music system developed using MVC and AngularJS. This application can be extended to add more features, like recently played songs and most played songs etc. as per your requirement.


Similar Articles