Fix Windows Relation on Audio and PDF Content Extraction ...

This commit is contained in:
2026-10-21 22:30:02 +03:30
parent ddfa7979a5
commit 907926b0f7
6 changed files with 133 additions and 207 deletions
@@ -1,15 +1,14 @@
using System;
using System.IO;
using FFMpegCore;
using System.Linq;
using Whisper.net;
using NAudio.Wave;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using NAudio.MediaFoundation;
using xAiApi.Interfaces.Extractors;
namespace xAiApi.Providers.Extractors
@@ -161,173 +160,76 @@ namespace xAiApi.Providers.Extractors
)
{
//
var result = await Task.Run(() =>
var tempInput = Path.Combine(
Path.GetTempPath(),
$"audio_in_{Guid.NewGuid()}{GetExtensionFromMime(mimeType)}"
);
var tempOutput = Path.Combine(
Path.GetTempPath(),
$"audio_out_{Guid.NewGuid()}.wav"
);
//
MemoryStream result = null;
try
{
//
var memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
memoryStream.Position = 0;
using var fs = File.Create(tempInput);
await inputStream.CopyToAsync(fs, cancellationToken);
await FFMpegArguments
.FromFileInput(tempInput)
.OutputToFile(tempOutput, overwrite: true, options => options
.WithAudioCodec("pcm_s16le")
.WithCustomArgument("-ar 16000")
.WithCustomArgument("-ac 1")
.ForceFormat("wav"))
.ProcessAsynchronously();
//
var targetFormat = new WaveFormat(16000, 16, 1);
string tempFilePath = null;
result = new();
using var fsTmp = File.OpenRead(tempOutput);
await fsTmp.CopyToAsync(result, cancellationToken);
result.Position = 0;
}
catch
{
result = null;
}
finally
{
//
try
{
//
WaveStream reader = GetAudioReader(memoryStream, mimeType, ref tempFilePath);
if (reader == null)
{
//
XException.NotAllowed.Throw(
$"Unsupported audio format: {mimeType}"
);
}
// Remove Temparory Files ...
if (File.Exists(tempInput)) File.Delete(tempInput);
if (File.Exists(tempOutput)) File.Delete(tempOutput);
}
//
var needsConversion =
reader.WaveFormat.SampleRate != 16000 ||
reader.WaveFormat.Channels != 1 ||
reader.WaveFormat.BitsPerSample != 16 ||
reader.WaveFormat.Encoding != WaveFormatEncoding.Pcm;
var outputStream = new MemoryStream();
if (!needsConversion)
{
//
reader.CopyTo(outputStream);
reader.Dispose();
}
else
{
//
MediaFoundationApi.Startup();
using var resampler = new MediaFoundationResampler(
reader,
targetFormat
);
resampler.ResamplerQuality = 60;
//
WaveFileWriter.WriteWavFileToStream(outputStream, resampler);
reader.Dispose();
}
//
outputStream.Position = 0;
return outputStream;
}
finally
{
//
if (!string.IsNullOrEmpty(tempFilePath) &&
File.Exists(tempFilePath))
{
//
try
{
File.Delete(tempFilePath);
}
catch { }
}
//
memoryStream.Dispose();
}
}, cancellationToken);
//
if (result.IsNull())
{
XException.ActionFailed.Throw();
}
//
return result;
}
/// <summary>
/// Get appropriate WaveStream reader based on MIME type ...
/// Retrieve File Extension based on mime type ...
/// </summary>
/// <param name="stream">Input stream (MemoryStream)</param>
/// <param name="mimeType">MIME type of audio file</param>
/// <param name="tempFilePath">Path to temp file (if created)</param>
/// <returns>WaveStream reader or null if unsupported</returns>
private WaveStream GetAudioReader(
MemoryStream stream,
string mimeType,
ref string tempFilePath
)
/// <param name="mimeType"></param>
/// <returns></returns>
private string GetExtensionFromMime(string mimeType)
{
//
try
return mimeType?.ToLowerInvariant() switch
{
//
var normalizedMime = mimeType?.ToLowerInvariant() ?? string.Empty;
switch (normalizedMime)
{
//
case "audio/wav":
case "audio/wave":
case "audio/x-wav":
return new WaveFileReader(stream);
//
case "audio/mpeg":
case "audio/mp3":
return new Mp3FileReader(stream);
//
case "audio/m4a":
case "audio/mp4":
case "audio/aac":
case "audio/ogg":
case "audio/webm":
case "audio/x-m4a":
//
var extension = normalizedMime switch
{
"audio/m4a" or "audio/mp4" or "audio/aac" or "audio/x-m4a" => ".m4a",
"audio/ogg" => ".ogg",
"audio/webm" => ".webm",
_ => ".tmp"
};
tempFilePath = Path.Combine(
Path.GetTempPath(),
$"audio_{Guid.NewGuid()}{extension}"
);
//
stream.Position = 0;
using (var fileStream = File.Create(tempFilePath))
{
stream.CopyTo(fileStream);
}
//
MediaFoundationApi.Startup();
return new MediaFoundationReader(tempFilePath);
default:
//
tempFilePath = Path.Combine(
Path.GetTempPath(),
$"audio_{Guid.NewGuid()}.tmp"
);
stream.Position = 0;
using (var fileStream = File.Create(tempFilePath))
{
stream.CopyTo(fileStream);
}
try
{
MediaFoundationApi.Startup();
return new MediaFoundationReader(tempFilePath);
}
catch
{
return null;
}
}
}
catch (Exception)
{
return null;
}
"audio/mpeg" or "audio/mp3" => ".mp3",
"audio/m4a" or "audio/mp4" or "audio/aac" or "audio/x-m4a" => ".m4a",
"audio/ogg" => ".ogg",
"audio/webm" => ".webm",
"audio/wav" or "audio/wave" or "audio/x-wav" => ".wav",
_ => ".tmp"
};
}
#endregion
}