1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
| [GeneratedComInterface] [Guid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")] public unsafe partial interface IMemoryBufferByteAccess { void GetBuffer(out byte* buffer, out uint capacity); }
public sealed partial class AudioGraphEngine : ISpectrumPlayer, IWaveformPlayer, INotifyPropertyChanged, IDisposable { private readonly DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread();
private AudioGraph graph; private AudioFileInputNode fileNode; private AudioDeviceOutputNode deviceNode; private AudioFrameOutputNode frameNode;
private readonly int fftDataSize = 2048; private readonly SampleAggregator sampleAggregator;
private bool isPlaying; private double channelLength; private double channelPosition;
public event PropertyChangedEventHandler PropertyChanged; private AudioSampleRingBuffer sampleBuffer; private CancellationTokenSource processingCts;
private TimeSpan playbackStartTime; public TimeSpan SelectionBegin { get; set; } public TimeSpan SelectionEnd { get; set; } public AudioGraphEngine() { sampleAggregator = new SampleAggregator(fftDataSize);
sampleBuffer = new AudioSampleRingBuffer(fftDataSize * 8); processingCts = new CancellationTokenSource(); StartProcessingLoop(); } private void StartProcessingLoop() { Task.Run(async () => { float left, right;
while (!processingCts.IsCancellationRequested) { if (sampleBuffer.TryRead(out left) && sampleBuffer.TryRead(out right)) { sampleAggregator.Add(left, right); } else { await Task.Delay(1); } } }, processingCts.Token); }
public bool GetFFTData(float[] fftDataBuffer) { sampleAggregator.GetFFTResults(fftDataBuffer); return IsPlaying; }
public int GetFFTFrequencyIndex(int frequency) { double maxFrequency = graph != null ? graph.EncodingProperties.SampleRate / 2.0 : 22050;
return (int)((frequency / maxFrequency) * (fftDataSize / 2)); }
public double ChannelPosition { get => channelPosition; set { if (fileNode == null) return;
value = Math.Max(0, Math.Min(value, ChannelLength)); fileNode.Seek(TimeSpan.FromSeconds(value)); channelPosition = value; NotifyPropertyChanged(nameof(ChannelPosition)); } }
public double ChannelLength { get => channelLength; private set { channelLength = value; NotifyPropertyChanged(nameof(ChannelLength)); } }
private float[] waveformData;
public float[] WaveformData { get => waveformData; private set { waveformData = value; NotifyPropertyChanged(nameof(WaveformData)); } } private async Task GenerateWaveformAsync(string wavPath) { await Task.Run(() => { byte[] data = File.ReadAllBytes(wavPath);
if (data.Length < 44) throw new InvalidOperationException("Invalid WAV file");
int channels = BitConverter.ToInt16(data, 22); int bitsPerSample = BitConverter.ToInt16(data, 34);
int dataChunkOffset = -1; int dataChunkSize = 0;
for (int i = 12; i < data.Length - 8;) { string chunkId = Encoding.ASCII.GetString(data, i, 4); int chunkSize = BitConverter.ToInt32(data, i + 4);
if (chunkId == "data") { dataChunkOffset = i + 8; dataChunkSize = chunkSize; break; }
i += 8 + chunkSize; }
if (dataChunkOffset < 0) throw new InvalidOperationException("WAV data chunk not found");
const int samplesPerBucket = 1024;
List<float> waveform = new();
float leftSumSq = 0, rightSumSq = 0; float leftPeak = 0, rightPeak = 0; int sampleCounter = 0;
int bytesPerSample = bitsPerSample / 8; int frameSize = bytesPerSample * channels;
for (int i = dataChunkOffset; i + frameSize <= dataChunkOffset + dataChunkSize; i += frameSize) { float l, r;
if (bitsPerSample == 16) { l = BitConverter.ToInt16(data, i) / 32768f; r = channels == 2 ? BitConverter.ToInt16(data, i + 2) / 32768f : l; } else if (bitsPerSample == 24) { int left = (data[i + 2] << 24) | (data[i + 1] << 16) | (data[i] << 8); left >>= 8; l = left / 8388608f;
if (channels == 2) { int right = (data[i + 5] << 24) | (data[i + 4] << 16) | (data[i + 3] << 8); right >>= 8; r = right / 8388608f; } else r = l; } else if (bitsPerSample == 32) { l = BitConverter.ToSingle(data, i); r = channels == 2 ? BitConverter.ToSingle(data, i + 4) : l; } else { throw new NotSupportedException($"Unsupported WAV bit depth: {bitsPerSample}"); }
leftPeak = Math.Max(leftPeak, Math.Abs(l)); rightPeak = Math.Max(rightPeak, Math.Abs(r));
leftSumSq += l * l; rightSumSq += r * r; sampleCounter++;
if (sampleCounter >= samplesPerBucket) { float leftRms = MathF.Sqrt(leftSumSq / sampleCounter); float rightRms = MathF.Sqrt(rightSumSq / sampleCounter);
waveform.Add((leftRms + leftPeak) * 0.5f); waveform.Add((rightRms + rightPeak) * 0.5f);
leftSumSq = rightSumSq = 0; leftPeak = rightPeak = 0; sampleCounter = 0; } }
float max = 0f; for (int i = 0; i < waveform.Count; i++) { float v = Math.Abs(waveform[i]); if (v > max) max = v; }
if (max > 0) { float gain = 1f / max; for (int i = 0; i < waveform.Count; i++) waveform[i] *= gain; }
dispatcherQueue.TryEnqueue(() => { WaveformData = waveform.ToArray(); }); }); }
public bool IsPlaying { get => isPlaying; private set { isPlaying = value; NotifyPropertyChanged(nameof(IsPlaying)); } }
public async Task OpenFile(string path) { DisposeGraph();
var file = await StorageFile.GetFileFromPathAsync(path);
await GenerateWaveformAsync(path);
var settings = new AudioGraphSettings(AudioRenderCategory.Media) { QuantumSizeSelectionMode = QuantumSizeSelectionMode.ClosestToDesired, DesiredSamplesPerQuantum = fftDataSize };
var graphResult = await AudioGraph.CreateAsync(settings); if (graphResult.Status != AudioGraphCreationStatus.Success) throw new InvalidOperationException("AudioGraph creation failed");
graph = graphResult.Graph;
var deviceResult = await graph.CreateDeviceOutputNodeAsync(); deviceNode = deviceResult.DeviceOutputNode;
var fileResult = await graph.CreateFileInputNodeAsync(file); fileNode = fileResult.FileInputNode;
frameNode = graph.CreateFrameOutputNode();
fileNode.AddOutgoingConnection(deviceNode); fileNode.AddOutgoingConnection(frameNode);
ChannelLength = fileNode.Duration.TotalSeconds;
graph.QuantumStarted += OnQuantumStarted; }
public void Play() { if (graph == null) return;
playbackStartTime = fileNode.Position; graph.Start(); IsPlaying = true; }
public void Pause() { if (graph == null) return;
graph.Stop(); IsPlaying = false; }
public void Stop() { if (graph == null) return;
graph.Stop(); fileNode.Seek(TimeSpan.Zero); ChannelPosition = 0; IsPlaying = false; }
private unsafe void OnQuantumStarted(AudioGraph sender, object args) { var frame = frameNode.GetFrame(); using var buffer = frame.LockBuffer(AudioBufferAccessMode.Read); using var reference = buffer.CreateReference();
((IMemoryBufferByteAccess)reference) .GetBuffer(out byte* data, out uint capacity);
float* samples = (float*)data; int count = (int)(capacity / sizeof(float));
for (int i = 0; i < count; i++) sampleBuffer.Write(samples[i]);
double positionSeconds = 0; if (fileNode != null && IsPlaying) positionSeconds = fileNode.Position.TotalSeconds;
dispatcherQueue.TryEnqueue(() => { channelPosition = positionSeconds; NotifyPropertyChanged(nameof(ChannelPosition)); }); }
public void Dispose() { DisposeGraph(); GC.SuppressFinalize(this); }
private void DisposeGraph() { if (graph != null) { graph.QuantumStarted -= OnQuantumStarted; graph.Stop(); graph.Dispose(); graph = null; }
fileNode = null; deviceNode = null; frameNode = null; } private void NotifyPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }
public sealed partial class AudioSampleRingBuffer { private readonly float[] buffer; private int writeIndex; private int readIndex;
public AudioSampleRingBuffer(int capacity) { buffer = new float[capacity]; }
public void Write(float value) { buffer[writeIndex] = value; writeIndex = (writeIndex + 1) % buffer.Length; }
public bool TryRead(out float value) { if (readIndex == writeIndex) { value = 0; return false; }
value = buffer[readIndex]; readIndex = (readIndex + 1) % buffer.Length; return true; } }
public static partial class FastFourierTransform { public static void FFT(Complex[] data, int exponent) { int n = 1 << exponent;
int j = 0; for (int i = 0; i < n; i++) { if (i < j) { var temp = data[i]; data[i] = data[j]; data[j] = temp; }
int m = n >> 1; while (j >= m && m >= 2) { j -= m; m >>= 1; } j += m; }
for (int stage = 1; stage <= exponent; stage++) { int step = 1 << stage; int halfStep = step >> 1;
double angleStep = -2.0 * Math.PI / step; Complex phaseStep = new Complex( Math.Cos(angleStep), Math.Sin(angleStep));
for (int k = 0; k < n; k += step) { Complex phase = Complex.One;
for (int i = 0; i < halfStep; i++) { int evenIndex = k + i; int oddIndex = evenIndex + halfStep;
Complex even = data[evenIndex]; Complex odd = phase * data[oddIndex];
data[evenIndex] = even + odd; data[oddIndex] = even - odd;
phase *= phaseStep; } } } } }
public sealed partial class SampleAggregator { private readonly int bufferSize; private readonly int fftExponent;
private readonly Complex[] channelData; private int channelDataPosition;
private float volumeLeftMaxValue; private float volumeLeftMinValue; private float volumeRightMaxValue; private float volumeRightMinValue;
public SampleAggregator(int bufferSize) { if ((bufferSize & (bufferSize - 1)) != 0) throw new ArgumentException("FFT buffer size must be a power of two");
this.bufferSize = bufferSize; fftExponent = (int)Math.Log(bufferSize, 2); channelData = new Complex[bufferSize];
Clear(); }
public void Clear() { volumeLeftMaxValue = float.MinValue; volumeRightMaxValue = float.MinValue; volumeLeftMinValue = float.MaxValue; volumeRightMinValue = float.MaxValue; channelDataPosition = 0; }
public void Add(float leftValue, float rightValue) { if (channelDataPosition == 0) { volumeLeftMaxValue = float.MinValue; volumeRightMaxValue = float.MinValue; volumeLeftMinValue = float.MaxValue; volumeRightMinValue = float.MaxValue; }
float mono = (leftValue + rightValue) * 0.5f;
channelData[channelDataPosition] = new Complex(mono, 0); channelDataPosition++;
volumeLeftMaxValue = Math.Max(volumeLeftMaxValue, leftValue); volumeLeftMinValue = Math.Min(volumeLeftMinValue, leftValue); volumeRightMaxValue = Math.Max(volumeRightMaxValue, rightValue); volumeRightMinValue = Math.Min(volumeRightMinValue, rightValue);
if (channelDataPosition >= bufferSize) channelDataPosition = 0; }
public void GetFFTResults(float[] fftBuffer) { if (fftBuffer == null) throw new ArgumentNullException(nameof(fftBuffer));
if (fftBuffer.Length < bufferSize / 2) throw new ArgumentException("FFT buffer is too small");
var fftData = new Complex[bufferSize]; Array.Copy(channelData, fftData, bufferSize);
FastFourierTransform.FFT(fftData, fftExponent);
for (int i = 0; i < bufferSize / 2; i++) { double real = fftData[i].Real; double imag = fftData[i].Imaginary;
fftBuffer[i] = (float)Math.Sqrt(real * real + imag * imag); } }
public float LeftMaxVolume => volumeLeftMaxValue; public float LeftMinVolume => volumeLeftMinValue; public float RightMaxVolume => volumeRightMaxValue; public float RightMinVolume => volumeRightMinValue; }
|