Server/Spectrum/BasicSpectrumProvider.cs
author StephaneLenclud
Sun, 08 Jan 2017 12:19:35 +0100
changeset 278 2481c46d1f93
permissions -rw-r--r--
Reading audio output is stopped when audio visualizers are not in used.
     1 using System;
     2 using System.Collections.Generic;
     3 using CSCore.DSP;
     4 
     5 namespace Visualization
     6 {
     7     /// <summary>
     8     ///     BasicSpectrumProvider
     9     /// </summary>
    10     public class BasicSpectrumProvider : FftProvider, ISpectrumProvider
    11     {
    12         private readonly int _sampleRate;
    13         private readonly List<object> _contexts = new List<object>();
    14 
    15         public BasicSpectrumProvider(int channels, int sampleRate, FftSize fftSize)
    16             : base(channels, fftSize)
    17         {
    18             if (sampleRate <= 0)
    19                 throw new ArgumentOutOfRangeException("sampleRate");
    20             _sampleRate = sampleRate;
    21         }
    22 
    23         public int GetFftBandIndex(float frequency)
    24         {
    25             int fftSize = (int)FftSize;
    26             double f = _sampleRate / 2.0;
    27             // ReSharper disable once PossibleLossOfFraction
    28             return (int)((frequency / f) * (fftSize / 2));
    29         }
    30 
    31         public bool GetFftData(float[] fftResultBuffer, object context)
    32         {
    33             if (_contexts.Contains(context))
    34                 return false;
    35 
    36             _contexts.Add(context);
    37             GetFftData(fftResultBuffer);
    38             return true;
    39         }
    40 
    41         public override void Add(float[] samples, int count)
    42         {
    43             base.Add(samples, count);
    44             if (count > 0)
    45                 _contexts.Clear();
    46         }
    47 
    48         public override void Add(float left, float right)
    49         {
    50             base.Add(left, right);
    51             _contexts.Clear();
    52         }
    53     }
    54 }