Insert Audio in Blazor RichTextEditor Component
18 Aug 202324 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 audio into the Rich Text Editor, the following list of options has been provided in the RichTextEditorAudioSettings.
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 video element when inserted. Possible options are Blob and Base64.
|
SaveUrl | Provides URL to map the action result method to save 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 RichTextEditorToolbarSettings.Items property.
To configure Audio
toolbar item, refer to the below code.
@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
<RichTextEditorToolbarSettings Items="@Items" />
</SfRichTextEditor>
@code {
private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
{
new ToolbarItemModel() { Command = ToolbarCommand.Audio }
};
}
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 RichTextEditorAudioSettings, the audio will be converted into Blob
url or Base64
and inserted inside the Rich Text Editor.
Restrict audio upload based on size
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.
@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
<RichTextEditorToolbarSettings Items="@Items" />
<RichTextEditorEvents FileUploading="@onFileUploading"></RichTextEditorEvents>
<RichTextEditorAudioSettings SaveUrl="https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save" Path="../Files/"></RichTextEditorAudioSettings>
</SfRichTextEditor>
@code {
private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
{
new ToolbarItemModel() { Command = ToolbarCommand.Audio }
};
private void onFileUploading(FileUploadingEventArgs args)
{
var imgSize = 500000;
var sizeInBytes = args.FilesData[0].Size;
if ( imgSize < sizeInBytes ) {
args.Cancel = true;
}
}
}
Server-side action
The selected audio can be uploaded to the required destination using the controller action below. Map this method name in RichTextEditorMediaSettings.SaveUrl and provide the required destination path through RichTextEditorMediaSettings.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
.
@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
<RichTextEditorToolbarSettings Items="@Items" />
<RichTextEditorAudioSettings SaveUrl="api/Audio/Save" Path="./Audio/"></RichTextEditorAudioSettings>
</SfRichTextEditor>
@code {
private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
{
new ToolbarItemModel() { Command = ToolbarCommand.Audio }
};
}
using System;
using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
namespace AudioUpload.Controllers
{
[ApiController]
public class AudioController : ControllerBase
{
private readonly IWebHostEnvironment hostingEnv;
public AudioController(IWebHostEnvironment env)
{
this.hostingEnv = env;
}
[HttpPost("[action]")]
[Route("api/Audio/Save")]
public void Save(IList<IFormFile> UploadFiles)
{
try
{
foreach (var file in UploadFiles)
{
if (UploadFiles != null)
{
string targetPath = hostingEnv.ContentRootPath + "\\wwwroot\\Audio";
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
// Create a new directory, if it does not exists
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
// Name which is used to save the audio
filename = targetPath + $@"\{filename}";
if (!System.IO.File.Exists(filename))
{
// Upload a audio, if the same file name does not exist in the directory
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
Response.StatusCode = 200;
}
else
{
Response.StatusCode = 204;
}
}
}
}
catch (Exception e)
{
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
}
}
}
}
Audio save format
The audio files can be saved as Blob
or Base64
url by using the RichTextEditorAudioSettings.SaveFormat property, which is of enum type and the generated url will be set to the src
attribute of the <source>
tag.
NOTE
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 RichTextEditorQuickToolbarSettings “Replace” 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 audio and click the Remove
tool from the quick toolbar. It will delete the audio from the Rich Text Editor content.
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.
Display Position
Sets the default display for an audio file when it is inserted in the Rich Text Editor using the RichTextEditorMediaSettings.layoutOption property. The possible options are inline
and break.
It also updates the audio elements’ layout position when updating the display positions.
NOTE
The default
layoutOption
property is set toInline
.
@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
<RichTextEditorToolbarSettings Items="@Items" />
<RichTextEditorAudioSettings LayoutOption="DisplayLayoutOptions.Break"></RichTextEditorAudioSettings>
<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>
</SfRichTextEditor>
@code {
private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
{
new ToolbarItemModel() { Command = ToolbarCommand.Audio }
};
}
Rename audio before inserting
Using the RichTextEditorAudioSettings property, specify the server handler to upload the selected audio. Then, by binding the FileUploadSuccess
event, you will 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.
@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
<RichTextEditorToolbarSettings Items="@Items" />
<RichTextEditorEvents FileUploadSuccess="@onFileUploadSuccess"></RichTextEditorEvents>
<RichTextEditorAudioSettings SaveUrl="api/Audio/Rename" Path="./Audio/"></RichTextEditorAudioSettings>
</SfRichTextEditor>
@code {
public string[] header { get; set; }
private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
{
new ToolbarItemModel() { Command = ToolbarCommand.Audio }
};
private void onFileUploadSuccess(FileUploadSuccessEventArgs args)
{
var headers = args.Response.Headers.ToString();
header = headers.Split("name: ");
header = header[1].Split("\r");
// Update the modified audio name to display a audio in the editor.
args.File.Name = header[0];
}
}
using System;
using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
namespace RenameAudio.Controllers
{
[ApiController]
public class AudioController : ControllerBase
{
private double x;
private string audiofileName;
private readonly IWebHostEnvironment hostingEnv;
public AudioController(IWebHostEnvironment env)
{
this.hostingEnv = env;
}
[HttpPost("[action]")]
[Route("api/Audio/Rename")]
public void Rename(IList<IFormFile> UploadFiles)
{
try
{
foreach (IFormFile file in UploadFiles)
{
if (UploadFiles != null)
{
string targetPath = hostingEnv.ContentRootPath + "\\wwwroot\\Audio";
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
// Create a new directory, if it does not exists
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
audiofileName = filename;
string path = hostingEnv.WebRootPath + "\\Images" + $@"\{filename}";
// Rename a uploaded audio file name
while (System.IO.File.Exists(path))
{
audiofileName = "rteImage" + x + "-" + filename;
path = hostingEnv.WebRootPath + "\\Images" + $@"\rteImage{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.Headers.Add("name", audiofileName);
Response.StatusCode = 200;
Response.ContentType = "application/json; charset=utf-8";
}
}
}
}
catch (Exception e)
{
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
}
}
}
}
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
UseDefaultCredentials
property, we need to manually append the default credentials with the upload request.
@using Syncfusion.Blazor.RichTextEditor;
<SfRichTextEditor>
<RichTextEditorToolbarSettings Items="@Items" />
<RichTextEditorEvents FileUploading="@onFileUploading"></RichTextEditorEvents>
<RichTextEditorAudioSettings SaveUrl="api/Audio/Save" Path="./Audio/"></RichTextEditorAudioSettings>
</SfRichTextEditor>
@code {
private List<ToolbarItemModel> Items = new List<ToolbarItemModel>()
{
new ToolbarItemModel() { Command = ToolbarCommand.Audio }
};
private void onFileUploading(FileUploadingEventArgs args)
{
var accessToken = "Authorization_token";
// adding custom Form Data
args.CustomFormData = new List<object> { new { Authorization = accessToken } };
}
}
using System;
using System.IO;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
namespace AudioUpload.Controllers
{
[ApiController]
public class AudioController : ControllerBase
{
private readonly IWebHostEnvironment hostingEnv;
public AudioController(IWebHostEnvironment env)
{
this.hostingEnv = env;
}
[HttpPost("[action]")]
[Route("api/Audio/Save")]
public void Save(IList<IFormFile> UploadFiles)
{
string currentPath = Request.Form["Authorization"].ToString();
try
{
foreach (var file in UploadFiles)
{
if (UploadFiles != null)
{
string targetPath = hostingEnv.ContentRootPath + "\\wwwroot\\Audio";
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
// Create a new directory, if it does not exists
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
// Name which is used to save the audio
filename = targetPath + $@"\{filename}";
if (!System.IO.File.Exists(filename))
{
// Upload a audio, if the same file name does not exist in the directory
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
Response.StatusCode = 200;
}
else
{
Response.StatusCode = 204;
}
}
}
}
catch (Exception e)
{
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
}
}
}
}