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.
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.
Code part
- 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.
-
-
-
-
-
-
-
-
- USE MASTER;
-
-
- 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
-
-
-
-
-
- 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
-
-
-
-
- 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
-
-
-
-
-
-
-
-
-
-
-
-
- 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
-
-
-
-
-
-
-
-
-
-
-
- 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
-
-
-
-
-
-
-
-
-
-
-
- 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
- USE musicPlayerDB
- GO
-
-
-
-
-
-
-
-
-
-
-
- Create PROCEDURE [dbo].[USP_KIDSLEARN_Delete]
- ( @KIDIDENTITY VARCHAR(20) = '' )
- AS
- BEGIN
- DELETE FROM kidsLearnerMaster WHERE KIDIDENTITY=@KIDIDENTITY
-
- 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.
-
- [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.
-
- [HttpGet]
- public IEnumerable<USP_MusicAlbum_SelectALL_Result> getMusicSelectALL(string AlbumName)
- {
- if (AlbumName == null)
- AlbumName = "";
-
- return objapi.USP_MusicAlbum_SelectALL(AlbumName).AsEnumerable();
- }
-
-
- [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();
-
- }
-
-
- [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();
-
- }
-
-
-
-
- [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”.
-
-
-
-
- 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.
- 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";
-
- $scope.AlbumIdentitys = 0;
- $scope.UImage = "";
- $scope.AlbumName = "";
-
-
- $scope.musicID = 0;
- $scope.SingerName = "";
- $scope.AlbumNameS = "RedAlbum";
- $scope.MusicFileName = "";
- $scope.Description = "";
-
-
-
- $scope.showMusicsAdd = false;
- $scope.showAlbum = true;
- $scope.showMusics = false;
- $scope.showEditMusics = false;
- 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.
-
- 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.
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.
- $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,
-
- $scope.$watch("f1.$valid", function (isValid) {
- $scope.IsFormValid = isValid;
- });
-
-
- $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;
- };
-
-
- $scope.selectFileforUpload = function (file) {
-
- var files = file[0];
- $scope.Imagename = files.name;
-
- $scope.SelectedFileForUpload = file[0];
-
- }
-
-
- $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.
-
-
-
-
- $scope.$watch("f2.$valid", function (isValid) {
- $scope.IsFormValid = isValid;
- });
-
-
-
-
-
-
- $scope.ChechMusicFileValid = function (file) {
- var isValid = false;
- if ($scope.selectmp3FileforUpload != null) {
- $scope.FileInvalidMessage = "";
- isValid = true;
- }
- else {
- $scope.FileInvalidMessage = "Music File required!";
- }
- $scope.IsFileValid = isValid;
- };
-
-
-
-
- $scope.selectmp3FileforUpload = function (file) {
- var files = file[0];
- $scope.MusicFileName = files.name;
-
- $scope.selectmp3FileforUpload = file[0];
-
- }
-
-
-
- $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 ($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 {
- $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.";
- }
-
- };
-
-
- $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;
- }
-
-
- $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.
-
-
-
-
- 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";
-
- $scope.AlbumIdentitys = 0;
- $scope.AlbumImage = "RedAlbum.jpg";
- $scope.AlbumName = "RedAlbu";
-
-
- $scope.musicID = 0;
- $scope.SingerName = "";
- $scope.AlbumNameS = "RedAlbum";
- $scope.MusicFileName = "";
- $scope.Description = "";
-
-
- $scope.selectedSongIndex = 0;
- $scope.songsCount = 0;
- $scope.CurrentSong = "Alarm06NOK.wav";
- $scope.selectedSongstoPlay = "/uploads/Alarm06NOK.wav";
-
-
- $scope.showAlbum = true;
- $scope.showMusics = false;
- $scope.showButton = false;
- $scope.showSounds = false;
-
-
- 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");
-
- $scope.showMusicAlbum = function showMusicAlbum(AlbumNames, ImageName) {
-
- $scope.AlbumName = AlbumNames;
- $scope.AlbumImage = ImageName;
-
-
- $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.
-
- $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.
-
- $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.
-
- $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.
-
- $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.
-
- $scope.playCurrent = function () {
- audio.play();
- }
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.