Insert Audio
22 Dec 202224 minutes to read
The Rich Text Editor allows inserting audio files from online sources and the local computer where you want to insert the audio in your content. For inserting the audio to the Rich Text Editor, the following list of options have been provided in the insertAudioSettings.
Options | Description |
---|---|
allowedTypes | Specifies the extensions of the audio types allowed to insert on bowering and passing the extensions with comma separators. For example, pass allowedTypes as .mp3 , .wav , .m4a and .wma
|
LayoutOption | Sets the default display for audio when it is inserted into the Rich Text Editor. Possible options are: Inline and Break . |
SaveFormat | Sets the default save format of the audio element when inserted. Possible options are: Blob and Base64 . |
SaveUrl | Provides URL to map the action result method to save the audio. |
RemoveUrl | Provides URL to map the action result method to remove the audio. |
Path | Specifies the location to store the audio. |
Configure audio tool in the toolbar
To include the audio tool in the Rich Text Editor, you can add the toolbar item Audio
to the toolbarSettings
items property.
To configure Audio
toolbar item, refer to the below code.
<ejs-richtexteditor id="editor">
<e-richtexteditor-toolbarsettings items="@ViewBag.items"></e-richtexteditor-toolbarsettings>
</ejs-richtexteditor>
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.items = new[] { "Audio" };
return View();
}
}
Insert audio from web
To insert audio from the hosted link or local machine, you should enable the audio tool on in the editor’s toolbar.
Insert from web URL
By default, the audio tool opens the audio dialog, allowing you to insert audio from an online source. Inserting the URL will be added to the src
attribute of the <source>
tag.
Upload and insert audio
In the audio dialog, using the browse
option, select the audio from the local machine and insert it into the Rich Text Editor content.
If the path field is not specified in the insertAudioSettings, the audio will be converted into Blob
url or Base64
and inserted inside the Rich Text Editor.
Restrict audio upload based on size
You can restrict the audio uploaded from the local machine when the uploaded audio file size is greater than the allowed size by using the FileUploading event.
NOTE
The file size in the argument will be returned in
bytes
.
Using the Rich Text Editor fileUploading
event, you can restrict the audio to upload when the given audio size is greater than the allowed fileSize. Also, the audio size in the argument will be returned in bytes
.
In the following illustration, the audio size has been validated before uploading, and it is determined whether the audio has been uploaded or not.
<ejs-richtexteditor id="editor" fileUploading="onFileUploading">
<e-richtexteditor-insertaudiosettings saveUrl="https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save" path="../Files/"></e-richtexteditor-insertaudiosettings>
<e-richtexteditor-toolbarsettings items="@ViewBag.items"></e-richtexteditor-toolbarsettings>
</ejs-richtexteditor>
<script>
function onFileUploading(args) {
var imgSize = 500000;
var sizeInBytes = args.fileData.size;
if ( imgSize < sizeInBytes ) {
args.cancel = true;
}
}
</script>
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.items = new[] { "Audio" };
return View();
}
}
Server-side action
The selected audio can be uploaded to the required destination using the controller action below. Map this method name in insertAudioSettings.saveUrl and provide required destination path through insertAudioSettings.path properties.
NOTE
If you want to insert lower-sized audio files in the editor and don’t want a specific physical location for saving audio, you can opt to save the format as
Base64
.
In the following code blocks, you can insert the audio files which are saved in the specified path.
<ejs-richtexteditor id="editor">
<e-richtexteditor-insertaudiosettings saveUrl="/Home/SaveFiles" path="./Files/"></e-richtexteditor-insertaudiosettings>
<e-richtexteditor-toolbarsettings items="@ViewBag.items"></e-richtexteditor-toolbarsettings>
</ejs-richtexteditor>
using System;
using System.IO;
using FileUpload.Models;
using System.Diagnostics;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
namespace FileUpload.Controllers
{
public class HomeController : Controller
{
private IHostingEnvironment hostingEnv;
public HomeController(IHostingEnvironment env)
{
hostingEnv = env;
}
public IActionResult Index()
{
ViewBag.items = new[] { "Audio" };
return View();
}
[AcceptVerbs("Post")]
public void SaveFiles(IList<IFormFile> UploadFiles)
{
try
{
foreach (IFormFile file in UploadFiles)
{
if (UploadFiles != null)
{
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
filename = hostingEnv.WebRootPath + "\\Files" + $@"\{filename}";
// Create a new directory, if it does not exists
if (!Directory.Exists(hostingEnv.WebRootPath + "\\Files"))
{
Directory.CreateDirectory(hostingEnv.WebRootPath + "\\Files");
}
if (!System.IO.File.Exists(filename))
{
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
Response.StatusCode = 200;
}
}
}
}
catch (Exception)
{
Response.StatusCode = 204;
}
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Audio save format
The audio files can be saved as Blob
or Base64
url by using the insertAudioSettings.saveFormat property, which is of enum type and the generated url will be set to the src
attribute of the <source>
tag.
NOTE
The default
saveFormat
property is set toBlob
format.
By default, the files are saved in the
Blob
format.
<audio>
<source src="blob:http://ej2.syncfusion.com/3ab56a6e-ec0d-490f-85a5-f0aeb0ad8879" type="audio/mp3" >
</audio>
<audio>
<source src="data:audio/mp3;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHA" type="audio/mp3" >
</audio>
Replacing audio
Once an audio file has been inserted, you can change it using the Rich Text Editor quickToolbarSettings audioReplace
option. You can replace the audio file using the web URL or the browse option in the audio dialog.
Delete audio
To remove audio from the Rich Text Editor content, select the audio and click the audioRemove
tool from the quick toolbar. It will delete the audio from the Rich Text Editor content as well as from the service location if the insertAudioSettings.removeUrl is given.
Once you select the audio from the local machine, the URL for the audio will be generated. You can remove the audio from the service location by clicking the cross icon.
The following sample explains how to configure insertAudioSettings.removeUrl
to remove saved audio from the remote service location when the following audio removal actions are performed:
-
delete
key action. -
backspace
key action. - Removing uploaded audio file from the insert audio dialog.
- Deleting audio using the quick toolbar
audioRemove
option.
NOTE
The default
layoutOption
property is set toInline
.
<ejs-richtexteditor id="rteImage">
<e-richtexteditor-insertimagesettings saveUrl="/Home/SaveImage" removeUrl="/Home/RemoveImage" path="../Uploads/" />
</ejs-richtexteditor>
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[AcceptVerbs("Post")]
public void SaveImage(HttpPostedFileBase UploadFiles)
{
try
{
if (UploadFiles != null)
{
string fileName = UploadFiles.FileName;
var fileSave = System.Web.HttpContext.Current.Server.MapPath("~/Uploads");
// Create a new directory, if it does not exists
if (!System.IO.Directory.Exists(fileSave))
{
System.IO.Directory.CreateDirectory(fileSave);
}
var fileSavePath = Path.Combine(fileSave, fileName);
// Save the image
UploadFiles.SaveAs(fileSavePath);
Response.StatusCode = 200;
Response.ContentType = "application/json; charset=utf-8";
}
}
catch (Exception)
{
Response.StatusCode = 204;
}
}
[AcceptVerbs("Post")]
public void RemoveImage(HttpPostedFileBase UploadFiles)
{
try
{
if (UploadFiles != null)
{
// Do remove action here
Response.StatusCode = 200;
Response.ContentType = "application/json; charset=utf-8";
}
}
catch (Exception)
{
Response.StatusCode = 204;
}
}
}
Display Position
Sets the default display for an audio when it is inserted in the Rich Text Editor using the insertAudioSettings.layoutOption
. It has two possible options: Inline
and Break
. When updating the display positions, it updates the audio elements’ layout position
<ejs-richtexteditor id="audio">
<e-richtexteditor-insertaudiosettings layoutOption="break"></e-richtexteditor-insertaudiosettings>
<e-richtexteditor-toolbarsettings items="@ViewBag.items"></e-richtexteditor-toolbarsettings>
<e-content-template>
<p>
The Rich Text Editor control is WYSIWYG ('what you see is what you get') editor that provides the best user experience to create and update the content.
Users can format their content using standard toolbar commands.
</p>
<p><b> Key features:</b></p>
<ul>
<li><p> Provides < IFRAME > and < DIV > modes </p></li>
<li><p> Capable of handling markdown editing.</p></li>
<li><p> Contains a modular library to load the necessary functionality on demand.</p></li>
<li><p> Provides a fully customizable toolbar.</p></li>
<li><p> Provides HTML view to edit the source directly for developers.</p></li>
<li><p> Supports third - party library integration.</p></li>
<li><p> Allows preview of modified content before saving it.</p></li>
<li><p> Handles images, hyperlinks, video, hyperlinks, uploads, etc.</p></li>
<li><p> Contains undo / redo manager.</p></li>
<li><p> Creates bulleted and numbered lists.</p></li>
</ul>
</e-content-template>
</ejs-richtexteditor>
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.items = new[] { "Audio" };
return View();
}
}
Rename audio before inserting
Using the insertAudioSettings property, you can specify the server handler to upload the selected audio. Then by binding the fileUploadSuccess
event, you can receive the modified file name from the server and update it in the Rich Text Editor’s insert audio dialog.
Refer rename.cs
controller file for configure the server-side.
<ejs-richtexteditor id="editor" fileUploadSuccess="onFileUploadSuccess">
<e-richtexteditor-insertaudiosettings saveUrl="/Home/Rename" path="./Uploads/"></e-richtexteditor-insertaudiosettings>
<e-richtexteditor-toolbarsettings items="@ViewBag.items"></e-richtexteditor-toolbarsettings>
</ejs-richtexteditor>
<script>
function onFileUploadSuccess(args) {
if (args.e.currentTarget.getResponseHeader('name') != null) {
args.file.name = args.e.currentTarget.getResponseHeader('name');
var filename = document.querySelectorAll(".e-file-name")[0];
filename.innerHTML = args.file.name.replace(document.querySelectorAll(".e-file-type")[0].innerHTML, '');
filename.title = args.file.name;
}
}
</script>
using System;
using System.IO;
using System.Diagnostics;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using RenameFile.Models;
namespace RenameFile.Controllers
{
public class HomeController : Controller
{
private int x = 0;
private string mediaFile;
private IHostingEnvironment hostingEnv;
public IActionResult Index()
{
ViewBag.items = new[] { "Audio" };
return View();
}
public HomeController(IHostingEnvironment env)
{
hostingEnv = env;
}
[HttpPost]
public void Rename(IList<IFormFile> UploadFiles)
{
try
{
foreach (IFormFile file in UploadFiles)
{
if (UploadFiles != null)
{
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
mediaFile = filename;
string path = hostingEnv.WebRootPath + "\\Uploads" + $@"\{filename}";
// Create a new directory, if it does not exists
if (!Directory.Exists(hostingEnv.WebRootPath + "\\Uploads"))
{
Directory.CreateDirectory(hostingEnv.WebRootPath + "\\Uploads");
}
// Rename a uploaded media file name
while (System.IO.File.Exists(path))
{
mediaFile = "rteAudio" + x + "-" + filename;
path = hostingEnv.WebRootPath + "\\Uploads" + $@"\rteAudio{x}-{filename}";
x++;
}
if (!System.IO.File.Exists(path))
{
using (FileStream fs = System.IO.File.Create(path))
{
file.CopyTo(fs);
fs.Flush();
fs.Close();
}
// Modified file name shared through response header by adding custom header
Response.StatusCode = 200;
Response.Headers.Add("name", mediaFile);
Response.ContentType = "application/json; charset=utf-8";
}
}
}
}
catch (Exception)
{
Response.StatusCode = 204;
}
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Upload audio with authentication
The Rich Text Editor control allows you to add additional data with the File Upload, which can be received on the server side. By using the fileUploading
event and its customFormData
argument, you can pass parameters to the controller action. On the server side, you can fetch the custom headers by accessing the form collection from the current request, which retrieves the values sent using the POST method.
NOTE
By default, it doesn’t support the
UseDefaultCredentials
property; we need to manually append the default credentials with the upload request.
By default it doesn’t support
UseDefaultCredentials
property, we need to manually append the default credentials with the upload request.
<ejs-richtexteditor id="editor" fileUploading="onFileUploading">
<e-richtexteditor-insertaudiosettings saveUrl="/Home/SaveFiles" path="./Files/"></e-richtexteditor-insertaudiosettings>
<e-richtexteditor-toolbarsettings items="@ViewBag.items"></e-richtexteditor-toolbarsettings>
</ejs-richtexteditor>
<script>
function onFileUploading(args) {
var accessToken = "Authorization_token";
// adding custom Form Data
args.customFormData = [{ 'Authorization': accessToken }];
}
</script>
using System;
using System.IO;
using FileUpload.Models;
using System.Diagnostics;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
namespace FileUpload.Controllers
{
public class HomeController : Controller
{
private IHostingEnvironment hostingEnv;
public HomeController(IHostingEnvironment env)
{
hostingEnv = env;
}
public IActionResult Index()
{
ViewBag.items = new[] { "Audio" };
return View();
}
[AcceptVerbs("Post")]
public void SaveFiles(IList<IFormFile> UploadFiles)
{
string currentPath = Request.Form["Authorization"].ToString();
try
{
foreach (IFormFile file in UploadFiles)
{
if (UploadFiles != null)
{
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
filename = hostingEnv.WebRootPath + "\\Files" + $@"\{filename}";
// Create a new directory, if it does not exists
if (!Directory.Exists(hostingEnv.WebRootPath + "\\Files"))
{
Directory.CreateDirectory(hostingEnv.WebRootPath + "\\Files");
}
if (!System.IO.File.Exists(filename))
{
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
Response.StatusCode = 200;
}
}
}
}
catch (Exception)
{
Response.StatusCode = 204;
}
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}