Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Creating Web Based Music Player System Using MVC and AngularJs

0.00/5 (No votes)
18 Sep 2016 1  
In this article, we will learn how to create a simple web based music player system using MVC, AngularJS and Web API.

Introduction

 

Click here to see the Vide Tutorial > Link to YouTube video.

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.

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

Album/Music CRUD (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

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

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.

Using the code

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. 

-- =============================================   
-- Author : Shanu   
-- Create date : 2016-02-28   
-- Description : To Create Database   
  
-- =============================================   
--Script to create DB,Table and sample Insert data   
  
USE MASTER;   
  
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB   
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'musicPlayerDB' )   
BEGIN   
ALTER DATABASE musicPlayerDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE   
DROP DATABASE musicPlayerDB ;   
END   
  
  
CREATE DATABASE musicPlayerDB   
GO   
  
USE musicPlayerDB   
GO   
  
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'AlbumMaster' )   
DROP TABLE AlbumMaster   
GO   
  
CREATE TABLE AlbumMaster   
(   
AlbumID int identity(1,1),   
AlbumName VARCHAR(200) NOT NULL ,   
ImageName VARCHAR(500) NOT NULL   
CONSTRAINT [PK_AlbumMaster] PRIMARY KEY CLUSTERED   
(   
[AlbumID] ASC   
  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]   
) ON [PRIMARY]   
  
Insert into AlbumMaster(AlbumName,ImageName) Values('RedAlbum','RedAlbum.jpg')  
  
select * from AlbumMaster   
  
  
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'MusicPlayerMaster' )   
DROP TABLE MusicPlayerMaster   
GO   
  
CREATE TABLE MusicPlayerMaster   
(   
MusicID int identity(1,1),   
SingerName VARCHAR(100) NOT NULL ,   
AlbumName VARCHAR(200) NOT NULL ,   
MusicFileName VARCHAR(500) NOT NULL,   
Description VARCHAR(100) NOT NULL,   
  
CONSTRAINT [PK_MusicPlayerMaster] PRIMARY KEY CLUSTERED   
(   
[MusicID] ASC   
  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]   
) ON [PRIMARY]   
  
select * from MusicPlayerMaster  

  Stored Procedure : Run all this procedure one by one in your SQL Server

SP to select all records of Album Details

USE musicPlayerDB   
GO   
  
-- =============================================   
-- To Select Albumdetails   
-- EXEC USP_AlbumMaster_Select ''   
-- =============================================   
CREATE PROCEDURE [dbo].[USP_AlbumMaster_Select]   
(   
@AlbumName VARCHAR(100) = ''   
)   
AS   
BEGIN   
SELECT AlbumID,AlbumName , ImageName  
FROM AlbumMaster   
WHERE   
AlbumName like @AlbumName +'%'   
Order By AlbumName  
END 

SP to Insert Album Details.

USE musicPlayerDB   
GO   
  
-- To insert  
-- EXEC [USP_Album_Insert] ''   
-- =============================================   
CREATE PROCEDURE [dbo].[USP_Album_Insert]   
(   
@AlbumName VARCHAR(200) = '',   
@ImageName VARCHAR(500) = ''  
)   
AS   
BEGIN   
IF NOT EXISTS (SELECT * FROM AlbumMaster WHERE AlbumName=@AlbumName)   
BEGIN   
  
INSERT INTO [dbo].AlbumMaster (AlbumName ,ImageName )  
VALUES (@AlbumName ,@ImageName )  
  
Select 'Inserted' as results   
  
END   
ELSE   
BEGIN   
Select 'Exists' as results   
END   
  
END    

SP to select all records of Music details

USE musicPlayerDB   
GO   
-- 1) select all MusicPlayerMaster records   
  
-- Author : Shanu   
-- Create date : 2016-08-23   
-- Description :select top 10 random kidsLearnerMaster records   
-- Tables used : MusicPlayerMaster   
-- Modifier : Shanu   
-- Modify date : 2016-08-23   
-- =============================================   
-- To Select all user roles   
-- EXEC USP_MusicAlbum_SelectALL ''   
-- =============================================   
CREATE PROCEDURE [dbo].[USP_MusicAlbum_SelectALL]   
(   
@AlbumName VARCHAR(100) = ''   
)   
AS   
BEGIN   
SELECT MusicID,   
SingerName ,   
AlbumName ,   
MusicFileName,   
Description   
FROM MusicPlayerMaster   
WHERE   
AlbumName like @AlbumName +'%'   
  
END  

SP to Insert Music Details

USE musicPlayerDB  
GO   
  
Insert MusicPlayerMaster records   
  
-- Author : Shanu   
-- Create date : 2016-08-23   
-- Description :Insert   
-- Tables used : MusicPlayerMaster   
-- Modifier : Shanu   
-- Modify date : 2016-08-23   
-- =============================================   
-- To insert  
-- EXEC USP_MusicAlbum_Insert ''   
-- =============================================   
CREATE PROCEDURE [dbo].[USP_MusicAlbum_Insert]   
(   
@SingerName VARCHAR(100) = '',   
@AlbumName VARCHAR(200) = '',   
@MusicFileName VARCHAR(500) = '',   
@Description VARCHAR(100) = ''  
)   
AS   
BEGIN   
IF NOT EXISTS (SELECT * FROM MusicPlayerMaster WHERE MusicFileName=@MusicFileName)   
BEGIN   
  
INSERT INTO [dbo].[MusicPlayerMaster]  
(SingerName ,AlbumName ,MusicFileName ,Description)  
VALUES  
(@SingerName ,@AlbumName ,@MusicFileName ,@Description)  
  
Select 'Inserted' as results   
  
END   
ELSE   
BEGIN   
Select 'Exists' as results   
END   
  
END    

SP to Update Music Details

USE musicPlayerDB   
GO   
Update all MusicPlayerMaster records   
  
-- Author : Shanu   
-- Create date : 2016-08-23   
-- Description :Update   
-- Tables used : MusicPlayerMaster   
-- Modifier : Shanu   
-- Modify date : 2016-08-23   
-- =============================================   
-- To Select all user roles   
-- EXEC USP_MusicAlbum_Update ''   
-- =============================================   
Create PROCEDURE [dbo].[USP_MusicAlbum_Update]   
(   
@musicID VARCHAR(20) = '',   
@SingerName VARCHAR(100) = '',   
@AlbumName VARCHAR(200) = '',   
@MusicFileName VARCHAR(500) = '',   
@Description VARCHAR(100) = ''  
)   
AS   
BEGIN   
UPDATE [dbo].[MusicPlayerMaster]  
SET [SingerName] = @SingerName,  
[AlbumName] = @AlbumName,  
[MusicFileName] = @MusicFileName,  
[Description] = @Description   
WHERE   
musicID = @musicID   
Select 'Updated' as results   
END 

SP to Delete record by Admin

-- =============================================    
-- To delete MusicAlbum record  
-- =============================================                                                            
Create PROCEDURE [dbo].[USP_MusicAlbum_Delete]                                                
   ( @musicID       VARCHAR(20)     = '' )                                                          
AS                                                                  
BEGIN         
        DELETE FROM MusicPlayerMaster WHERE musicID=@musicID                   
              
END   

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. 

Select MVC,WEB API and click OK.

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,

<system.web>  
<httpRuntime   executionTimeout="3600" maxRequestLength="102400" />   
  </system.web>  
  
<system.webServer>  
<security>  
        <requestFiltering>  
            <requestLimits maxAllowedContentLength="104857600" />  
        </requestFiltering>  
    </security>  
  </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.

Select "EF Designer from database" and click Next.

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

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

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. 

// To select Album Details  
       [HttpGet]  
       public IEnumerable<USP_AlbumMaster_Select_Result> getAlbums(string AlbumName)  
       {  
           if (AlbumName == null)  
               AlbumName = "";  
           return objapi.USP_AlbumMaster_Select(AlbumName).AsEnumerable();  
       }   

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. 

[HttpGet]  
        public IEnumerable<string> insertAlbum(string AlbumName, string ImageName)  
        {  
            if (AlbumName == null)  
                AlbumName = "";  
  
            if (ImageName == null)  
                ImageName = "";  
  
            return objapi.USP_Album_Insert(AlbumName, ImageName).AsEnumerable();  
  
        }  

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.

// to Search all Music Album Details  
[HttpGet]  
public IEnumerable<USP_MusicAlbum_SelectALL_Result> getMusicSelectALL(string AlbumName)  
{  
    if (AlbumName == null)  
        AlbumName = "";  
  
    return objapi.USP_MusicAlbum_SelectALL(AlbumName).AsEnumerable();  
}  
  
// To insert Music Details  
[HttpGet]  
public IEnumerable<string> insertMusic(string SingerName, string AlbumName, string MusicFileName, string Description)  
{  
    if (SingerName == null)  
        SingerName = "";  
  
    if (MusicFileName == null)  
        MusicFileName = "";  
  
    if (AlbumName == null)  
        AlbumName = "";  
  
    if (Description == null)  
        Description = "";  
  
    return objapi.USP_MusicAlbum_Insert(SingerName, AlbumName, MusicFileName, Description).AsEnumerable();  
  
}  
  
// To Update Music Details  
[HttpGet]  
public IEnumerable<string> updateMusic(string musicID, string SingerName, string AlbumName, string MusicFileName, string Description)  
{  
    if (musicID == null)  
        musicID = "0";  
  
    if (SingerName == null)  
        SingerName = "";  
  
    if (MusicFileName == null)  
        MusicFileName = "";  
  
    if (AlbumName == null)  
        AlbumName = "";  
  
    if (Description == null)  
        Description = "";  
  
    return objapi.USP_MusicAlbum_Update(musicID, SingerName, AlbumName, MusicFileName, Description).AsEnumerable();  
  
}  
  
// To Delete Music Details  
[HttpGet]  
public IEnumerable<string> deleteMusic(string musicID)  
{  
    if (musicID == null)  
        musicID = "0";  
    return objapi.USP_MusicAlbum_Delete(musicID).AsEnumerable();  
  
}  

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)

Creating AngularJS Controller 

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

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”.

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.

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”. 

// <reference path="../angular.js" />    
/// <reference path="../angular.min.js" />     
/// <reference path="../angular-animate.js" />     
/// <reference path="../angular-animate.min.js" />     
var app;  
(function () {  
    app = angular.module("AngularJs_Module", ['ngAnimate']);  
})();

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. 
app.controller("AngularJs_Controller", function ($scope, $timeout, $rootScope, $window, $http , FileUploadService) {  
    $scope.date = new Date();  
    $scope.MyName = "shanu";  
    // For Album Details  
    $scope.AlbumIdentitys = 0;  
    $scope.UImage = "";  
    $scope.AlbumName = "";  
  
    // For Music Details  
    $scope.musicID = 0;  
    $scope.SingerName = "";  
    $scope.AlbumNameS = "RedAlbum";  
    $scope.MusicFileName = "";  
    $scope.Description = "";  
  
    //For Visible design  
  
    $scope.showMusicsAdd = false;  
    $scope.showAlbum = true;  
    $scope.showMusics = false;  
    $scope.showEditMusics = false;  

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. 

// This method is to get all the kids Learn Details to display for CRUD.   
    selectAlbumDetails($scope.AlbumName);  
  
    function selectAlbumDetails(AlbumName) {  
        $http.get('/api/MusicAPI/getAlbums/', { params: { AlbumName: AlbumName } }).success(function (data) {  
            $scope.AlbumData = data;  
            
            if ($scope.AlbumData.length > 0) {  
            }  
        })  
   .error(function () {  
       $scope.error = "An Error has occured while loading posts!";  
   });  
  
        $http.get('/api/MusicAPI/getMusicSelectALL/', { params: { AlbumName: AlbumName } }).success(function (data) {  
            $scope.MusicData = data;  
  
            if ($scope.AlbumData.length > 0) {  
            }  
        })  
  .error(function () {  
      $scope.error = "An Error has occured while loading posts!";  
  });  
    }  

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.

$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.

$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,

//Form Validation  
    $scope.$watch("f1.$valid", function (isValid) {  
        $scope.IsFormValid = isValid;  
    });  
  
    //File Validation  
    $scope.ChechFileValid = function (file) {  
        var isValid = false;  
        if ($scope.SelectedFileForUpload != null) {  
            if ((file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') && file.size <= (800 * 800)) {  
                $scope.FileInvalidMessage = "";  
                isValid = true;  
            }  
            else {  
                $scope.FileInvalidMessage = "Only JPEG/PNG/Gif Image can be upload )";  
            }  
        }  
        else {  
            $scope.FileInvalidMessage = "Image required!";  
        }  
        $scope.IsFileValid = isValid;  
    };  
  
    //File Select event   
    $scope.selectFileforUpload = function (file) {  
  
        var files = file[0];  
        $scope.Imagename = files.name;  
        //    alert($scope.Imagename);  
        $scope.SelectedFileForUpload = file[0];  
  
    }  
  
    //Save Album File  
    $scope.saveAlbum = function () {  
        $scope.IsFormSubmitted = true;  
  
        $scope.Message = "";  
        $scope.ChechFileValid($scope.SelectedFileForUpload);  
  
        if ($scope.IsFormValid && $scope.IsFileValid) {  
            FileUploadService.UploadFile($scope.SelectedFileForUpload).then(function (d) {  
  
                $http.get('/api/MusicAPI/insertAlbum/', { params: { AlbumName: $scope.AlbumName, ImageName: $scope.Imagename } }).success(function (data) {  
                    $scope.menuInserted = data;  
                    alert($scope.menuInserted);  
                    cleardetails();  
                    selectAlbumDetails('');  
                })  
         .error(function () {  
             $scope.error = "An Error has occured while loading posts!";  
         });  
  
            }, function (e) {  
                alert(e);  
            });  
        }  
        else {  
            $scope.Message = "All the fields are required.";  
        }  
  
    };  
  
  
.factory('FileUploadService', function ($http, $q) {  
    
    var fac = {};  
    fac.UploadFile = function (file) {  
        var formData = new FormData();  
        formData.append("file", file);  
  
        var defer = $q.defer();  
        $http.post("/KidslearnAdmin/UploadFile", formData,  
            {  
                withCredentials: true,  
                headers: { 'Content-Type': undefined },  
                transformRequest: angular.identity  
            })  
        .success(function (d) {  
            defer.resolve(d);  
        })  
        .error(function () {  
            defer.reject("File Upload Failed!");  
        });  
  
        return defer.promise;  
  
    }  
    return fac;  

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.

// ********   Music CRUD Management and MP3 File Upload    
          
    //Form Validation  
    $scope.$watch("f2.$valid", function (isValid) {  
        $scope.IsFormValid = isValid;  
    });  
  
    // THIS IS REQUIRED AS File Control is not supported 2 way binding features of Angular  
    // ------------------------------------------------------------------------------------    
  
    //File Validation  
    $scope.ChechMusicFileValid = function (file) {  
        var isValid = false;  
        if ($scope.selectmp3FileforUpload != null) {  
            $scope.FileInvalidMessage = "";  
            isValid = true;  
        }  
        else {  
            $scope.FileInvalidMessage = "Music File required!";  
        }  
        $scope.IsFileValid = isValid;  
    };  
  
    //to upload Music File  
  
    //File Select event   
    $scope.selectmp3FileforUpload = function (file) {          
        var files = file[0];         
        $scope.MusicFileName = files.name;  
        //    alert($scope.Imagename);  
        $scope.selectmp3FileforUpload = file[0];    
    }    
  
    //Save Music  File  
    $scope.saveMusicDetails = function () {  
          
        $scope.IsFormSubmitted = true;  
  
        $scope.Message = "";             
  
        $scope.ChechMusicFileValid($scope.selectmp3FileforUpload);            
  
        if ($scope.IsFormValid && $scope.IsFileValid) {  
            
            FileUploadService.UploadFile($scope.selectmp3FileforUpload).then(function (d) {  
                 
                //if the Music ID=0 means its new Music insert here i will call the Web api insert method  
                if ($scope.musicID == 0) {  
  
                    $http.get('/api/MusicAPI/insertMusic/', { params: { SingerName: $scope.SingerName, AlbumName: $scope.AlbumNameS, MusicFileName: $scope.MusicFileName, Description: $scope.Description } }).success(function (data) {  
  
                        $scope.menuInserted = data;  
                        alert($scope.menuInserted);   
  
                        cleardetails();  
                        selectAlbumDetails('');  
                    })  
             .error(function () {  
                 $scope.error = "An Error has occured while loading posts!";  
             });  
                }  
  
  
                else {  // to update to the Music details  
                    $http.get('/api/MusicAPI/updateMusic/', { params: { musicID: $scope.musicID, SingerName: $scope.SingerName, AlbumName: $scope.AlbumNameS, MusicFileName: $scope.MusicFileName, Description: $scope.Description } }).success(function (data) {  
                        $scope.menuUpdated = data;  
                        alert($scope.menuUpdated);  
  
                        cleardetails();  
                        selectAlbumDetails('');  
                    })  
            .error(function () {  
                $scope.error = "An Error has occured while loading posts!";  
            });  
                }  
  
            }, function (e) {  
                alert(e);  
            });  
        }  
        else {  
            $scope.Message = "All the fields are required.";  
        }  
  
    };  
  
    //Edit MusicEdit  Details  
    $scope.MusicEdit = function KidsEdit(musicID, SingerName, AlbumName, MusicFileName, Description) {  
        cleardetails();  
        $scope.showEditMusics = true;  
        alert(musicID);  
        $scope.musicID = musicID;  
        $scope.SingerName = SingerName;  
        $scope.AlbumNameS = AlbumName;  
        $scope.MusicFileName = MusicFileName;  
        $scope.Description = Description;  
    }  
  
    //Delete MusicDelete Detail  
    $scope.MusicDelete = function KidsDelete(musicIDs) {  
        cleardetails();  
        $scope.showEditMusics = true;  
        $scope.musicID = musicIDs;  
        var delConfirm = confirm("Are you sure you want to delete the Kids Lear Detail ?");  
        if (delConfirm == true) {  
  
            $http.get('/api/MusicAPI/deleteMusic/', { params: { musicID: $scope.musicID } }).success(function (data) {  
                alert("Music Detail Deleted Successfully!!");  
                cleardetails();  
                selectAlbumDetails('');  
            })  
      .error(function () {  
          $scope.error = "An Error has occured while loading posts!";  
      });  
  
        }  
    }  

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. 

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.

// <reference path="../angular.js" />    
/// <reference path="../angular.min.js" />     
/// <reference path="../angular-animate.js" />     
/// <reference path="../angular-animate.min.js" />     
var app;  
(function () {  
    app = angular.module("AngularJsHome_Module", ['ngAnimate']);  
})();    
  
app.controller("AngularJsHome_Controller", function ($scope, $timeout, $rootScope, $window, $http) {  
    $scope.date = new Date();  
    $scope.MyName = "shanu";  
    // For Album Details  
    $scope.AlbumIdentitys = 0;  
    $scope.AlbumImage = "RedAlbum.jpg";  
    $scope.AlbumName = "RedAlbu";  
  
    // For Music Details  
    $scope.musicID = 0;  
    $scope.SingerName = "";  
    $scope.AlbumNameS = "RedAlbum";  
    $scope.MusicFileName = "";  
    $scope.Description = "";  
  
    // Play Songs  
    $scope.selectedSongIndex = 0;  
    $scope.songsCount = 0;  
    $scope.CurrentSong = "Alarm06NOK.wav";  
    $scope.selectedSongstoPlay = "/uploads/Alarm06NOK.wav";  
    //For Visible design  
   
    $scope.showAlbum = true;  
    $scope.showMusics = false;  
    $scope.showButton = false;  
    $scope.showSounds = false;  
    
    // This method is to get all the kids Learn Details to display for CRUD.   
    selectAlbumDetails('');  
  
    function selectAlbumDetails(AlbumName) {  
        $http.get('/api/MusicAPI/getAlbums/', { params: { AlbumName: AlbumName } }).success(function (data) {  
            $scope.AlbumData = data;  
  
            if ($scope.AlbumData.length > 0) {  
            }  
        })  
   .error(function () {  
       $scope.error = "An Error has occured while loading posts!";  
   });  
  
        
    }  

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.In html part, we use this style in div tag to display 3 columns per row.

<div class="columns">  
                            <div ng-repeat="details in AlbumData">  
                                <table style='width: 99%;table-layout:fixed;'>  
                                    <tr>  
                                        <td align="center">  
                                            <img src="~/uploads/{{details.ImageName}}" alt="{{details.ImageName}}" width="144px" height="144px" ng-click="showMusicAlbum(details.AlbumName, details.ImageName)" />  
                                        </td>  
                                    </tr>  
                                    <tr>  
                                        <td align="center">  
                                            <span style="color:#257815;font-size:large"><b>{{details.AlbumName}}</b></span>  
  
                                        </td>  
                                    </tr>  
                                    <tr>  
                                        <td>  
  
                                            <img src="~/Images/blank.gif" alt="" width="1" height="2" />  
                                        </td>  
                                    </tr>  
                                </table>  
                            </div>  
                        </div>  

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.

<audio id="audioPlay">  
  <source  src="{{selectedSongstoPlay}}"></source>  
 </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.

var audio = document.getElementById("audioPlay");  
    //Show Music   Details  
    $scope.showMusicAlbum = function showMusicAlbum(AlbumNames, ImageName) {  
  
        $scope.AlbumName = AlbumNames;  
        $scope.AlbumImage = ImageName;  
           
        // Get the Music Play list by Albums  
        $http.get('/api/MusicAPI/getMusicSelectALL/', { params: { AlbumName: $scope.AlbumName } }).success(function (data) {  
            $scope.MusicData = data;  
             
            if ($scope.MusicData.length > 0) {  
                $scope.showAlbum = false;  
                $scope.showMusics = true;  
                $scope.showButton = true;  
                $scope.songsCount=$scope.MusicData.length;  
                $scope.selectedSongIndex = 0;  
                $scope.CurrentSong = $scope.MusicData[$scope.selectedSongIndex].MusicFileName;  
                $scope.playMusic($scope.selectedSongIndex, $scope.CurrentSong);  
            }  
            else  
            {  
                alert("No Songs has been added in this Album")  
                $scope.songsCount = 0;  
                $scope.selectedSongIndex = 0;  
            }  
             
        })  
.error(function () {  
    $scope.error = "An Error has occured while loading posts!";  
});  
    }  

In playMusic, we get the music file name and play the current selected songs.

//Play Songs  
    $scope.playMusic = function (indexnumber, musicFileName) {  
        $scope.selectedSongIndex = indexnumber;  
        $scope.CurrentSong = musicFileName;  
    $scope.selectedSongstoPlay = "/uploads/" + musicFileName;       
    
        audio.load();  
        audio.play();  
  
        audio.addEventListener('ended', function () {  
            if ($scope.selectedSongIndex < $scope.songsCount) {  
                $scope.selectedSongIndex = $scope.selectedSongIndex + 1;  
            }  
            else {  
                $scope.selectedSongIndex = 0;  
            }  
  
            $scope.CurrentSong = $scope.MusicData[$scope.selectedSongIndex].MusicFileName;  
            $scope.selectedSongstoPlay = "/uploads/" + musicFileName;  
  
            audio.load();  
            audio.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.

//next Song Play  
    $scope.nextSong = function () {  
        if ($scope.selectedSongIndex < $scope.songsCount) {  
            $scope.selectedSongIndex = $scope.selectedSongIndex + 1;  
        }  
        else {  
            $scope.selectedSongIndex = 0;  
        }  
  
        $scope.CurrentSong = $scope.MusicData[$scope.selectedSongIndex].MusicFileName;  
        $scope.playMusic($scope.selectedSongIndex, $scope.CurrentSong);  
    }  

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.

//Previous Song Play  
    $scope.previousSong = function ()  
    {  
        if($scope.selectedSongIndex>0)  
        {  
            $scope.selectedSongIndex = $scope.selectedSongIndex - 1;  
        }  
        else  
        {  
            $scope.selectedSongIndex = 0;  
        }  
  
        $scope.CurrentSong = $scope.MusicData[$scope.selectedSongIndex].MusicFileName;  
        $scope.playMusic($scope.selectedSongIndex, $scope.CurrentSong);  
    } 

Pause Current Song
In stop image click, we call the pauseMusic method .In this method, we pause the currently playing song.

//Pause Songs  
   $scope.pauseMusic = function () {  
       audio.pause();  
   } 

Play Current Song 
In play image click, we call the playCurrent method .In this method we continue playing of paused song.

//play Current Songs  
    $scope.playCurrent = function () {        
        audio.play();  
    } 

Points of Interest

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.

History

shanuMusicPlayerMVC.zip - 2016-09-01

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here