Skip to content

Commit

Permalink
replace naudio (doesn't work outside windows)
Browse files Browse the repository at this point in the history
  • Loading branch information
dclipca committed Dec 6, 2024
1 parent a23323a commit 6dde82a
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 46 deletions.
38 changes: 22 additions & 16 deletions FakeYou.NET.Tests/Integration/FakeYouClientIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@
using FluentAssertions;
using FakeYou.NET.Client;
using Microsoft.Extensions.Logging;
using NAudio.Wave;
using FakeYou.NET.Tests.Utils;
using System.Diagnostics;
using Xunit.Abstractions;
using FakeYou.NET.Audio;

namespace FakeYou.NET.Tests.Integration
{
[Collection("FakeYou Tests")]
public class FakeYouClientIntegrationTests : IDisposable
{

private readonly ILogger<FakeYouClientIntegrationTests> _logger;
private readonly FakeYouClient _client;
private readonly CancellationTokenSource _cts;
Expand Down Expand Up @@ -73,20 +71,28 @@ public async Task GenerateAudioAsync_ProducesValidWavFile()
audioData.Should().NotBeNull();
audioData.Length.Should().BeGreaterThan(44, "WAV file should be larger than header size");

using (var stream = new MemoryStream(audioData))
using (var reader = new WaveFileReader(stream))
{
_logger.LogInformation("Generated audio format:");
_logger.LogInformation($"- Sample Rate: {reader.WaveFormat.SampleRate}");
_logger.LogInformation($"- Channels: {reader.WaveFormat.Channels}");
_logger.LogInformation($"- Bits Per Sample: {reader.WaveFormat.BitsPerSample}");
_logger.LogInformation($"- Audio Length: {reader.Length} bytes");
// Read WAV header information
var processor = new AudioProcessor(_logger);
processor.ValidateWavFormat(audioData).Should().BeTrue("Should be valid WAV format");

// Get format details directly from the WAV header
var sampleRate = BitConverter.ToInt32(audioData, 24);
var channels = BitConverter.ToUInt16(audioData, 22);
var bitsPerSample = BitConverter.ToUInt16(audioData, 34);
var dataSize = BitConverter.ToInt32(audioData, 40);

_logger.LogInformation("Generated audio format:");
_logger.LogInformation($"- Sample Rate: {sampleRate}");
_logger.LogInformation($"- Channels: {channels}");
_logger.LogInformation($"- Bits Per Sample: {bitsPerSample}");
_logger.LogInformation($"- Audio Length: {dataSize} bytes");

reader.WaveFormat.Encoding.Should().Be(WaveFormatEncoding.Pcm);
reader.WaveFormat.BitsPerSample.Should().Be(16);
reader.WaveFormat.Channels.Should().BeInRange(1, 2);
reader.WaveFormat.SampleRate.Should().BeOneOf(44100, 48000);
}
// Verify format
var formatCode = BitConverter.ToInt16(audioData, 20);
formatCode.Should().Be(1, "Should be PCM format");
bitsPerSample.Should().Be(16);
channels.Should().BeInRange(1, 2);
sampleRate.Should().BeOneOf(44100, 48000);

var outputPath = Path.Combine(Path.GetTempPath(), "fakeyou_test_output.wav");
await File.WriteAllBytesAsync(outputPath, audioData);
Expand Down
60 changes: 32 additions & 28 deletions FakeYou.NET/Audio/AudioProcessor.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using NAudio.Wave;
using Microsoft.Extensions.Logging;
using System.Text;

namespace FakeYou.NET.Audio
{
Expand All @@ -14,35 +14,29 @@ public AudioProcessor(ILogger? logger = null)

public byte[] ConvertToWav(byte[] audioData, WavFormat format)
{
_logger?.LogDebug("Starting audio conversion to {SampleRate}Hz, {BitsPerSample}-bit, {Channels} channels",
_logger?.LogDebug("Processing audio format {SampleRate}Hz, {BitsPerSample}-bit, {Channels} channels",
format.SampleRate, format.BitsPerSample, format.Channels);

using var inputStream = new MemoryStream(audioData);
using var reader = new WaveFileReader(inputStream);
if (!ValidateWavFormat(audioData))
{
_logger?.LogDebug("Invalid WAV format, ensuring valid header");
return EnsureValidWavHeader(audioData, format);
}

_logger?.LogDebug("Input format: {Format}", reader.WaveFormat);
// Read the input format
var inputFormat = ReadWavFormat(audioData);
_logger?.LogDebug("Input format: {SampleRate}Hz, {BitsPerSample}-bit, {Channels} channels",
inputFormat.SampleRate, inputFormat.BitsPerSample, inputFormat.Channels);

if (!NeedsConversion(reader.WaveFormat, format))
if (!NeedsConversion(inputFormat, format))
{
_logger?.LogDebug("Audio format matches target, no conversion needed");
return audioData;
}

var targetFormat = new WaveFormat(
format.SampleRate,
format.BitsPerSample,
format.Channels);

_logger?.LogDebug("Converting to format: {Format}", targetFormat);

using var converter = new WaveFormatConversionStream(targetFormat, reader);
using var outputStream = new MemoryStream();
WaveFileWriter.WriteWavFileToStream(outputStream, converter);

var result = outputStream.ToArray();
_logger?.LogDebug("Audio conversion complete, output size: {Size} bytes", result.Length);

return result;
// For now, just ensure valid header if formats don't match
// In future we could implement actual format conversion if needed
return EnsureValidWavHeader(audioData, format);
}

public bool ValidateWavFormat(byte[] audioData)
Expand Down Expand Up @@ -82,12 +76,12 @@ public byte[] EnsureValidWavHeader(byte[] data, WavFormat format)
var header = new byte[44];

// RIFF header
System.Text.Encoding.ASCII.GetBytes("RIFF").CopyTo(header, 0);
Encoding.ASCII.GetBytes("RIFF").CopyTo(header, 0);
BitConverter.GetBytes((uint)(data.Length - 8)).CopyTo(header, 4);
System.Text.Encoding.ASCII.GetBytes("WAVE").CopyTo(header, 8);
Encoding.ASCII.GetBytes("WAVE").CopyTo(header, 8);

// Format chunk
System.Text.Encoding.ASCII.GetBytes("fmt ").CopyTo(header, 12);
Encoding.ASCII.GetBytes("fmt ").CopyTo(header, 12);
BitConverter.GetBytes((uint)16).CopyTo(header, 16);
BitConverter.GetBytes((ushort)1).CopyTo(header, 20);
BitConverter.GetBytes((ushort)format.Channels).CopyTo(header, 22);
Expand All @@ -99,7 +93,7 @@ public byte[] EnsureValidWavHeader(byte[] data, WavFormat format)
BitConverter.GetBytes((ushort)format.BitsPerSample).CopyTo(header, 34);

// Data chunk
System.Text.Encoding.ASCII.GetBytes("data").CopyTo(header, 36);
Encoding.ASCII.GetBytes("data").CopyTo(header, 36);
BitConverter.GetBytes((uint)(data.Length - 44)).CopyTo(header, 40);

var result = new byte[data.Length];
Expand All @@ -108,16 +102,26 @@ public byte[] EnsureValidWavHeader(byte[] data, WavFormat format)

return result;
}

private bool VerifyBytes(byte[] data, int offset, string expected)
{
var actual = System.Text.Encoding.ASCII.GetString(data, offset, expected.Length);
var actual = Encoding.ASCII.GetString(data, offset, expected.Length);
return actual == expected;
}

private bool NeedsConversion(WaveFormat current, WavFormat target) =>
private bool NeedsConversion(WavFormat current, WavFormat target) =>
current.SampleRate != target.SampleRate ||
current.BitsPerSample != target.BitsPerSample ||
current.Channels != target.Channels;

private WavFormat ReadWavFormat(byte[] data)
{
return new WavFormat
{
Channels = BitConverter.ToUInt16(data, 22),
SampleRate = BitConverter.ToInt32(data, 24),
BitsPerSample = BitConverter.ToUInt16(data, 34)
};
}
}
}
2 changes: 0 additions & 2 deletions FakeYou.NET/FakeYou.NET.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.4" Condition="'$(TargetFramework)' == 'net6.0'" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" Condition="'$(TargetFramework)' == 'net7.0'" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.0" Condition="'$(TargetFramework)' == 'net8.0'" />

<PackageReference Include="NAudio" Version="2.2.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Polly" Version="8.5.0" />
</ItemGroup>
Expand Down

0 comments on commit 6dde82a

Please sign in to comment.