How To Dynamically Upload And Play Audio File Using MVC 5

This article demonstrates how to upload audio files up to 50MB and play dynamically using ASP.NET MVC 5.

Introduction

This article demonstrates how to upload an audio file up to 50MB and play dynamically using ASP.NET MVC 5. I will upload the audio file in my project folder (AudioFileUpload) and its path in SQL Server database table.

I will retrieve (display) all the uploaded audio files and their related data in HTML table with sorting, searching, and paging functionality using Bootstrap 4 and jQuery data table plugin. We will understand this step by step.

Step 1

Create a database in SQL Server of your choice.

  1. CREATE TABLE [dbo].[AudioFiles](  
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [FileSize] [intNULL,  
  5.     [FilePath] [nvarchar](100) NULL,  
  6.  CONSTRAINT [PK_AudioFiles] PRIMARY KEY CLUSTERED   
  7. (  
  8.     [ID] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY]  
  11.   
  12. GO  
  13.   
  14. CREATE procedure [dbo].[spAddNewAudioFile]  
  15. (  
  16. @Name nvarchar(50),  
  17. @FileSize int,  
  18. @FilePath nvarchar(100)  
  19. )  
  20. as  
  21. begin  
  22. insert into AudioFiles (Name,FileSize,FilePath)   
  23. values (@Name,@FileSize,@FilePath)   
  24. end  
  25.   
  26. CREATE procedure [dbo].[spGetAllAudioFile]  
  27. as  
  28. begin  
  29. select ID,Name,FileSize,FilePath from AudioFiles  
  30. end  
ASP.NET

Step 2

Create an empty ASP.NET Web Application project in Visual Studio 2015. As shown in the below screenshot, open Visual Studio ( VS 2015 in my case). Click on the new project, choose web template >> choose ASP.NET Web Application, and give it a meaningful name. Then, click OK.

ASP.NET

Choose empty from ASP.NET Templates, select checkbox MVC, and click on OK.

ASP.NET

Step 3

Double click and open webconfig file to add the database connection.

  1. <connectionStrings>  
  2.     <add name="DBCS" connectionString="data source=FARHAN\SQLEXPRESS; database=MvcDemo; integrated security=true;" />     
  3.   </connectionStrings>  

Add this below code in webconfig file to allow 50MB file to upload.

  1. <httpRuntime executionTimeout="3600" maxRequestLength="51200" enable="true" />  
  2.   
  3. <system.webServer>  
  4.     <security>  
  5.       <requestFiltering>  
  6.         <requestLimits maxAllowedContentLength="104857600" />  
  7.       </requestFiltering>  
  8.     </security>  
  9.   </system.webServer>  

Step 4

Right-click on the project, add New Folder, name it AudioFileUpload to upload all audio files in that folder.

Step 5

Right click on Models folder, select Add >> Class.

Screenshot for creating model class-1

ASP.NET

A window will appear. Choose Class, give it a name as AudioFile, then click on Add.

Screenshot for creating model class-2

ASP.NET

Write class field and property as we have in the database table.

  1. using System;  
  2.   
  3. namespace MvcUploadAudioFile_Demo.Model  
  4. {  
  5.     public class AudioFile  
  6.     {  
  7.         public int ID { get; set; }  
  8.         public string Name { get; set; }  
  9.         public Nullable<int> FileSize { get; set; }  
  10.         public string FilePath { get; set; }  
  11.     }  
  12. }  

Step 6

Right-click on Controllers folder, select Add >> Controller. Name it as HomeController.

Screenshot for creating controller 1

ASP.NET

After clicking on Controller, a window will appear. Choose MVC 5 Controller-Empty and click on Add.

Screenshot for creating controller 2

ASP.NET

After that, another window will appear with DefaultController highlighted by default. Change the default to HomeController. Remember, don’t change suffix name of the Controller here. Click on Add and the Home controller will be added to the Controllers folder.

Screenshot for creating controller 3

ASP.NET

Add the following namespace in Controller class

  1. using MvcUploadAudioFile_Demo.Model;  
  2. using System.Data;  
  3. using System.Data.SqlClient;  
  4. using System.Configuration;  
  5. using System.IO;  

Create UploadAudio action method with [HttpGet] in controller. Write the following code to retrieve the data from database table.

  1. [HttpGet]  
  2.  public ActionResult UploadAudio()  
  3.  {  
  4.      List<AudioFile> audiolist = new List<AudioFile>();  
  5.      string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  6.      using (SqlConnection con = new SqlConnection(CS))  
  7.      {  
  8.          SqlCommand cmd = new SqlCommand("spGetAllAudioFile", con);  
  9.          cmd.CommandType = CommandType.StoredProcedure;  
  10.          con.Open();  
  11.          SqlDataReader rdr = cmd.ExecuteReader();  
  12.          while (rdr.Read())  
  13.          {  
  14.              AudioFile audio = new AudioFile();  
  15.              audio.ID = Convert.ToInt32(rdr["ID"]);  
  16.              audio.Name = rdr["Name"].ToString();  
  17.              audio.FileSize = Convert.ToInt32(rdr["FileSize"]);  
  18.              audio.FilePath = rdr["FilePath"].ToString();  
  19.   
  20.              audiolist.Add(audio);  
  21.          }  
  22.      }  
  23.      return View(audiolist);  
  24.  }  

Create UploadAudio action method with [HttpPost] in controller. Write the following code to insert data into database and upload file in AudioFileUpload folder of project.

  1. [HttpPost]  
  2.      public ActionResult UploadAudio(HttpPostedFileBase fileupload)  
  3.      {  
  4.          if (fileupload != null)  
  5.          {  
  6.              string fileName = Path.GetFileName(fileupload.FileName);                
  7.              int fileSize = fileupload.ContentLength;  
  8.              int Size = fileSize/1000000;  
  9.              fileupload.SaveAs(Server.MapPath("~/AudioFileUpload/" + fileName));  
  10.   
  11.              string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  12.              using (SqlConnection con = new SqlConnection(CS))  
  13.              {  
  14.                  SqlCommand cmd = new SqlCommand("spAddNewAudioFile", con);  
  15.                  cmd.CommandType = CommandType.StoredProcedure;  
  16.                  con.Open();  
  17.                  cmd.Parameters.AddWithValue("@Name", fileName);  
  18.                  cmd.Parameters.AddWithValue("@FileSize", Size);  
  19.                  cmd.Parameters.AddWithValue("FilePath""~/AudioFileUpload/" + fileName);  
  20.                  cmd.ExecuteNonQuery();  
  21.              }  
  22.          }  
  23.          return RedirectToAction("UploadAudio");  
  24.      }  

Complete code for HomeController to insert and retrieve file.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web;  
  4. using System.Web.Mvc;  
  5. using MvcUploadAudioFile_Demo.Model;  
  6. using System.Data;  
  7. using System.Data.SqlClient;  
  8. using System.Configuration;  
  9. using System.IO;  
  10.   
  11. namespace MvcUploadAudioFile_Demo.Controllers  
  12. {  
  13.     public class HomeController : Controller  
  14.     {  
  15.         public ActionResult Index()  
  16.         {  
  17.             return View();  
  18.         }  
  19.         [HttpGet]  
  20.         public ActionResult UploadAudio()  
  21.         {  
  22.             List<AudioFile> audiolist = new List<AudioFile>();  
  23.             string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  24.             using (SqlConnection con = new SqlConnection(CS))  
  25.             {  
  26.                 SqlCommand cmd = new SqlCommand("spGetAllAudioFile", con);  
  27.                 cmd.CommandType = CommandType.StoredProcedure;  
  28.                 con.Open();  
  29.                 SqlDataReader rdr = cmd.ExecuteReader();  
  30.                 while (rdr.Read())  
  31.                 {  
  32.                     AudioFile audio = new AudioFile();  
  33.                     audio.ID = Convert.ToInt32(rdr["ID"]);  
  34.                     audio.Name = rdr["Name"].ToString();  
  35.                     audio.FileSize = Convert.ToInt32(rdr["FileSize"]);  
  36.                     audio.FilePath = rdr["FilePath"].ToString();  
  37.   
  38.                     audiolist.Add(audio);  
  39.                 }  
  40.             }  
  41.             return View(audiolist);  
  42.         }  
  43.         [HttpPost]  
  44.         public ActionResult UploadAudio(HttpPostedFileBase fileupload)  
  45.         {  
  46.             if (fileupload != null)  
  47.             {  
  48.                 string fileName = Path.GetFileName(fileupload.FileName);                
  49.                 int fileSize = fileupload.ContentLength;  
  50.                 int Size = fileSize/1000000;  
  51.                 fileupload.SaveAs(Server.MapPath("~/AudioFileUpload/" + fileName));  
  52.   
  53.                 string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  54.                 using (SqlConnection con = new SqlConnection(CS))  
  55.                 {  
  56.                     SqlCommand cmd = new SqlCommand("spAddNewAudioFile", con);  
  57.                     cmd.CommandType = CommandType.StoredProcedure;  
  58.                     con.Open();  
  59.                     cmd.Parameters.AddWithValue("@Name", fileName);  
  60.                     cmd.Parameters.AddWithValue("@FileSize", Size);  
  61.                     cmd.Parameters.AddWithValue("FilePath""~/AudioFileUpload/" + fileName);  
  62.                     cmd.ExecuteNonQuery();  
  63.                 }  
  64.             }  
  65.             return RedirectToAction("UploadAudio");  
  66.         }  
  67.     }  
  68. }  

Step 7

Right-click on UploadAudio action method and Add View (uncheck use a layout page). Click on Add.

ASP.NET

Add the following jQuery script and bootstrap file in the head section of the View page. Download or add package from NuGet Package Manager, click on Tools => NuGet Package Manager => Manage NuGet Package for the solution.

Select Browse, type bootstrap in search bar, select and install similar jQuery. All downloaded files will be in Content and scripts.
  1. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  2. <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  3. <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  4. <script src="~/scripts/bootstrap.min.js"></script>  
  5. <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />  
  6. <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>  
  7. <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>  

Write the below jQuery script to avoid playing all audios at the same time. This script will allow you to play one audio at a time and pause others when you play an audio.

  1. <script type="text/javascript" >  
  2.      $(document).ready(function () {  
  3.          $('#dataTable').DataTable();  
  4.   
  5.          $("audio").on("play"function () {  
  6.              $("audio").not(this).each(function (index, audio) {  
  7.                  audio.pause();  
  8.              });  
  9.          });  
  10.      });  
  11.  </script>  

Design of the complete  HTML page in UploadAudio View.

  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6.   
  7. <html>  
  8. <head>  
  9.     <meta name="viewport" content="width=device-width" />  
  10.     <title>UploadAudio</title>  
  11.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  12.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  13.     <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  14.     <script src="~/scripts/bootstrap.min.js"></script>  
  15.     <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />  
  16.     <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>  
  17.     <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>  
  18.     <script>  
  19.         $(document).ready(function () {  
  20.             $('#dataTable').DataTable();  
  21.   
  22.             $("audio").on("play"function () {  
  23.                 $("audio").not(this).each(function (index, audio) {  
  24.                     audio.pause();  
  25.                 });  
  26.   
  27.             });  
  28.         });  
  29.     </script>  
  30. </head>  
  31. <body>  
  32.     <div class="container py-4">  
  33.         <h3 class="text-center text-uppercase">How to upload and play audio from database in mvc5</h3>  
  34.         <div class="card">  
  35.             <div class="card-header bg-primary text-white">  
  36.                 <h6 class="text-uppercase">Audio List</h6>  
  37.             </div>  
  38.             <div class="card-body">  
  39.                 <div class="row">  
  40.                     <button style="margin-left: 27px;margin-bottom:10px;" type="button" class="btn btn-primary rounded-0" data-toggle="modal" data-target="#myModal">  
  41.                         <i class="fa fa-plus-circle"></i> Add New  
  42.                     </button>  
  43.                     <div class="modal fade" id="myModal">  
  44.                         <div class="modal-dialog">  
  45.                             <div class="modal-content">  
  46.                                 <div class="modal-header">  
  47.                                     <h4 class="modal-title">Upload New Audio File</h4>  
  48.                                     <button type="button" class="close" data-dismiss="modal">×</button>  
  49.                                 </div>  
  50.                                 <div class="modal-body">  
  51.                                     @using (Html.BeginForm("UploadAudio""Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  52.                                     {  
  53.   
  54.                                         <div class="form-group">  
  55.                                             <label>Choose File:</label>  
  56.                                             <div class="input-group">  
  57.                                                 <div class="custom-file">  
  58.                                                     <input type="file" id="fileupload" name="fileupload" class="custom-file-input" />  
  59.                                                     <label class="custom-file-label"></label>  
  60.                                                 </div>  
  61.                                                 <div class="input-group-append">  
  62.                                                     <input type="submit" id="btnUpload" class="btn btn-secondary" value="Upload" />  
  63.                                                 </div>  
  64.                                             </div>  
  65.                                         </div>  
  66.                                     }  
  67.                                 </div>  
  68.                                 <div class="modal-footer">  
  69.                                     <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>  
  70.                                 </div>  
  71.   
  72.                             </div>  
  73.                         </div>  
  74.                     </div>  
  75.                 </div>  
  76.                 <table id="dataTable" class="table table-bordered table-striped">  
  77.                     <thead>  
  78.                         <tr>  
  79.                             <th>ID</th>  
  80.                             <th>Name</th>  
  81.                             <th>File Size(MB)</th>  
  82.                             <th>Play Audio</th>  
  83.                         </tr>  
  84.                     </thead>  
  85.                     <tbody>  
  86.                         @foreach (var item in Model)  
  87.                         {  
  88.                             <tr>  
  89.   
  90.                                 <td>@item.ID</td>  
  91.                                 <td>@item.Name</td>  
  92.                                 <td>@item.FileSize</td>  
  93.                                 <td>  
  94.                                     <audio controls>  
  95.                                         <source src="@Url.Content(@item.FilePath)" type="audio/ogg">  
  96.                                     </audio>  
  97.                                 </td>  
  98.   
  99.                             </tr>  
  100.                         }  
  101.                     </tbody>  
  102.                 </table>  
  103.             </div>  
  104.         </div>  
  105.     </div>  
  106. </body>  
  107. </html>  

Step 8

Run the project by pressing Ctr+F5.

Screenshot 1

ASP.NET

Screenshot 2

ASP.NET

Screenshot 3

ASP.NET

Conclusion

In this article, I have explained how to upload and play audio files up to 50MB in size using ASP.NET MVC5. I have used Bootstrap 4 and jQuery datatable plugin for searching, shorting and paging.