Audios in ASP.NET MVC Rich text editor Control

21 Mar 202520 minutes to read

The Rich Text Editor allows you to insert audio from online sources and local computers and then insert them into your content. You can insert the audio with the following list of options in the InsertAudioSettings property.

Configuring the Audio Tool in the Toolbar

You can add an Audio tool in the Rich Text Editor toolbar using the ToolbarSettings Items property.

To configure the Audio toolbar item, refer to the below code.

@Html.EJS().RichTextEditor("editor").ToolbarSettings(e => e.Items((object)ViewBag.items)).Value(ViewBag.value).Render()
public class HomeController : Controller
{

    public ActionResult Index()
    {
        ViewBag.value = @"<p>The Syncfudion Rich Text Editor, a WYSIWYG (what you see is what you get) editor, is a user interface that allows you to create, edit, and format rich text content. You can try out a demo of this editor here.</p><p><b>Key features:</b></p><ul><li><p>Provides &lt;IFRAME&gt; and &lt;DIV&gt; modes.</p></li><li><p>Bulleted and numbered lists.</p></li><li><p>Handles images, hyperlinks, videos, hyperlinks, uploads, etc.</p></li><li><p>Contains undo/redo manager. </p></li></ul><div style='display: inline-block; width: 60%; vertical-align: top; cursor: auto;'><img alt='Sky with sun' src='https://cdn.syncfusion.com/ej2/richtexteditor-resources/RTE-Overview.png' width='309' style='min-width: 10px; min-height: 10px; width: 309px; height: 174px;' class='e-rte-image e-imginline e-rte-drag-image' height='174' /></div>";
        ViewBag.items = new[] { "Audio" };
        return View();
    }
}

Audio Save Formats

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.

The default SaveFormat property is set to 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>

Insert Audio from the Web

You can insert audio from either the hosted link or the local machine, by clicking the audio button in the editor’s toolbar. On clicking the audio button, a dialog opens, which allows you to insert audio from the web URL.

Inserting Audio from Web URLs

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.

Rich Text Editor Audio insert

Uploading Audio from Local Machine

You can use the browse option on the audio dialog, to 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 the Blob URL or Base64 and inserted inside the Rich Text Editor.

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 the required destination path through InsertAudioSettings.Path properties.

If you want to insert lower-sized audio files in the editor and don’t want a specific physical location for saving the audio, you can opt to save the format as Base64.

@Html.EJS().RichTextEditor("defaultRTE").ToolbarSettings(e => e.Items((object)ViewBag.items)).InsertAudioSettings(obj => obj.SaveUrl("/Home/SaveFiles").Path("../Files/")).Render()
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace FileUpload.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.items = new[] { "Audio" };
            return View();
        }

        [AcceptVerbs("Post")]
        public void SaveFiles(HttpPostedFileBase UploadFiles)
        {
            if (UploadFiles != null)
            {
                string path = Server.MapPath("~/Files/");

                // Create a new directory, if it does not exists
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                // Save a file in directory
                UploadFiles.SaveAs(path + Path.GetFileName(UploadFiles.FileName));
            }
        }
    }
}

Saving Audio to the Server

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.

Renaming Audio Before Inserting

You can use the InsertAudioSettings property, to 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.

@Html.EJS().RichTextEditor("editor").ToolbarSettings(e => e.Items((object)ViewBag.items)).InsertAudioSettings(obj => obj.SaveUrl("/Home/Rename").Path("../Uploads/")).FileUploadSuccess("onFileUploadSuccess").Render()

<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.Web;
using System.Web.Mvc;

namespace RenameFile.Controllers
{
    public class HomeController : Controller
    {
        int x = 0;
        string filename;

        public ActionResult Index()
        {
            ViewBag.items = new[] { "Audio" };
            return View();
        }

        [AcceptVerbs("Post")]
        public void Rename(HttpPostedFileBase UploadFiles)
        {
            try
            {
                if (UploadFiles != null)
                {
                    filename = UploadFiles.FileName;

                    if (UploadFiles != null)
                    {
                        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 fileName = Path.GetFileName(UploadFiles.FileName);
                        var fileSavePath = Path.Combine(fileSave, fileName);

                        // Rename a uploaded file name
                        while (System.IO.File.Exists(fileSavePath))
                        {
                            filename = "rteAudio" + x + "-" + fileName;
                            fileSavePath = Path.Combine(fileSave, filename);
                            x++;
                        }

                        if (!System.IO.File.Exists(fileSavePath))
                        {
                            UploadFiles.SaveAs(fileSavePath);

                            // Modified file name shared through response header by adding custom header
                            Response.Headers.Add("name", filename);
                            Response.StatusCode = 200;
                            Response.ContentType = "application/json; charset=utf-8";
                        }
                    }
                }
            }
            catch (Exception)
            {
                Response.StatusCode = 204;
            }
        }
    }
}

Restricting Audio by 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.

The file 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.

@Html.EJS().RichTextEditor("editor").ToolbarSettings(e => e.Items((object)ViewBag.items)).InsertAudioSettings(obj => obj.SaveUrl("https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save").Path("../Files/")).FileUploading("onFileUploading").Render()

<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();
    }
}

Uploading Audio with Authentication

You can add additional data with the audio uploaded from the Rich Text Editor on the client side, which can even 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.

@Html.EJS().RichTextEditor("defaultRTE").ToolbarSettings(e => e.Items((object)ViewBag.items)).InsertAudioSettings(obj => obj.SaveUrl("/Home/SaveFiles").FileUploading("onFileUploading").Path("../Files/")).Render()

<script>
    function onFileUploading(args) {
        var accessToken = "Authorization_token";
        // adding custom Form Data
        args.customFormData = [{ 'Authorization': accessToken }];
    }
</script>
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace FileUpload.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.items = new[] { "Audio" };
            return View();
        }

        [AcceptVerbs("Post")]
        public void SaveFiles(HttpPostedFileBase UploadFiles)
        {
            string currentPath = Request.Form["Authorization"].ToString();
            if (UploadFiles != null)
            {
                string path = Server.MapPath("~/Files/");

                // Create a new directory, if it does not exists
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                // Save a file in directory
                UploadFiles.SaveAs(path + Path.GetFileName(UploadFiles.FileName));
            }
        }
    }
}

Audio Replacement Functionality

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.

Rich Text Editor Audio replace

Deleting Audios

To remove audio from the Rich Text Editor content, select the audio and click the audioRemove button 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.

Rich Text Editor Audio delete

Configuring Audio Display Position

Sets the default display property for audio when it is inserted in the Rich Text Editor using the InsertAudioSettings.LayoutOption property. It has two possible options: Inline and Break. When updating the display positions, it updates the audio elements’ layout position.

The default layoutOption property is set to Inline.

@Html.EJS().RichTextEditor("audio").ToolbarSettings(e => e.Items((object)ViewBag.items)).InsertAudioSettings(obj => obj.LayoutOption("Break")).Value(ViewBag.value).Render()
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.value = @"<p>The Syncfudion Rich Text Editor, a WYSIWYG (what you see is what you get) editor, is a user interface that allows you to create, edit, and format rich text content. You can try out a demo of this editor here.</p><p><b>Key features:</b></p><ul><li><p>Provides &lt;IFRAME&gt; and &lt;DIV&gt; modes.</p></li><li><p>Bulleted and numbered lists.</p></li><li><p>Handles images, hyperlinks, videos, hyperlinks, uploads, etc.</p></li><li><p>Contains undo/redo manager. </p></li></ul><div style='display: inline-block; width: 60%; vertical-align: top; cursor: auto;'><img alt='Sky with sun' src='https://cdn.syncfusion.com/ej2/richtexteditor-resources/RTE-Overview.png' width='309' style='min-width: 10px; min-height: 10px; width: 309px; height: 174px;' class='e-rte-image e-imginline e-rte-drag-image' height='174' /></div>";
        ViewBag.items = new[] { "Audio" };
        return View();
    }
}

Customizing the Audio Quick Toolbar

The Rich Text Editor enables customization of the audio quick toolbar, allowing you to tailor its functionality with essential tools such as AudioReplace, Remove, and AudioLayoutOption.

By configuring these options in the QuickToolbarSettings property, you enhance the editor’s capabilities, facilitating seamless management and editing of audio directly within your content. This customization ensures a user-friendly experience for manipulating audio elements efficiently.

@Html.EJS().RichTextEditor("audio-quick-toolbar").ToolbarSettings(e => e.Items((object)ViewBag.items)).QuickToolbarSettings(e => { e.Audio((object)ViewBag.audio); }).Value(ViewBag.value).Render()
public class HomeController : Controller
{

    public ActionResult Index()
    {
        ViewBag.value = @"<p><b>Get started with Quick Toolbar to click on an audio</b></p>
                    <p>Using the quick toolbar, users can replace, display, and delete the selected audio.</p>
                    <p><audio controls><source src='https://cdn.syncfusion.com/ej2/richtexteditor-resources/RTE-Audio.wav' type='audio/mp3' /></audio></p>";
        ViewBag.items = new[] { "Audio" };
        ViewBag.audio = new[] { "AudioReplace", "Remove", "AudioLayoutOption"};
        return View();
    }
}

See Also