Это мой код:
Код: Выделить всё
@if (Question.Parcours.Type == Constants.TypeLanguage)
{
@if (FileAudio != null)
{
}
@if (Managing)
{
@if (recording)
{
En cours d'enregistrement...
[i][/i] Arrêter d'enregistrer l'audio
}
else
{
[i][/i] Commencer à enregistrer l'audio
}
}
@if (ErrorMessage != null)
{
@ErrorMessage
}
}
@code {
[Parameter] public QuestionDto Question { get; set; }
[Parameter] public bool Managing { get; set; } = true;
[Inject] IJSRuntime JS { get; set; }
private byte[] audioBytes;
private bool recording = false;
private string? FileAudio { get; set; }
private bool DisableStopRecoredingBtn { get; set; } = false;
private string AudioDirectory = Path.Combine("Fichiers", "AudiosLangue");
private string? ErrorMessage { get; set; } = null;
private string MessagePermissionDenied = "Vous devez permettre à l'application d'accéder à votre micro!";
protected override async Task OnInitializedAsync()
{
if (Question?.AudioFilePath != null)
{
var audioStream = GetAudioFileStream(Question.AudioFilePath);
if (audioStream != null)
FileAudio = await GetBase64Audio(audioStream);
}
}
private async Task StartRecording()
{
try
{
ErrorMessage = null;
await JS.InvokeVoidAsync("startRecording");
recording = true;
StateHasChanged();
await Task.Delay(60000);
if (recording)
{
await StopRecording();
}
}
catch (Exception ex)
{
ErrorMessage = MessagePermissionDenied;
}
}
private async Task StopRecording()
{
try
{
DisableStopRecoredingBtn = true;
audioBytes = await JS.InvokeAsync("stopRecording");
const int maxFileSize = 5 * 1024 * 1024;
if (audioBytes.Length > maxFileSize)
{
ErrorMessage = "Le fichier est trop gros, le maximum est de 5 MB.";
return;
}
if (!Directory.Exists(AudioDirectory))
{
Directory.CreateDirectory(AudioDirectory);
}
var randomFileName = $"P{Question.ParcoursId}-Q{Question.Id}-{Path.GetRandomFileName()}.mp3";
var filePath = Path.Combine(AudioDirectory, randomFileName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
await File.WriteAllBytesAsync(filePath, audioBytes);
Question.AudioFilePath = filePath;
var fileStream = GetAudioFileStream(filePath);
FileAudio = await GetBase64Audio(fileStream);
recording = false;
DisableStopRecoredingBtn = false;
StateHasChanged();
}
catch (Exception ex)
{
ErrorMessage = MessagePermissionDenied;
}
}
private Stream GetAudioFileStream(string filePath)
{
if (File.Exists(filePath))
{
return new FileStream(filePath, FileMode.Open, FileAccess.Read);
}
return null;
}
private async Task GetBase64Audio(Stream stream)
{
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream);
byte[] byteArray = memoryStream.ToArray();
string base64String = Convert.ToBase64String(byteArray);
return $"data:audio/mp3;base64,{base64String}";
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... ked-on-ios