44using System . Drawing . Imaging ;
55using System . Numerics ;
66using System . Runtime . InteropServices ;
7+ using System . Threading . Tasks ;
78
89namespace Spectrogram
910{
@@ -16,10 +17,10 @@ public class Spectrogram
1617 private readonly List < double [ ] > ffts = new List < double [ ] > ( ) ;
1718 private readonly List < double > newAudio = new List < double > ( ) ;
1819
19- public Spectrogram ( int sampleRate , int fftSize , int windowSize , int stepSize ,
20+ public Spectrogram ( int sampleRate , int fftSize , int stepSize ,
2021 double minFreq = 0 , double maxFreq = double . PositiveInfinity )
2122 {
22- settings = new Settings ( sampleRate , fftSize , windowSize , stepSize , minFreq , maxFreq ) ;
23+ settings = new Settings ( sampleRate , fftSize , stepSize , minFreq , maxFreq ) ;
2324 }
2425
2526 public void Add ( double [ ] audio )
@@ -29,26 +30,30 @@ public void Add(double[] audio)
2930
3031 public void Process ( )
3132 {
32- int fftsToProcess = ( newAudio . Count - settings . WindowSize ) / settings . StepSize ;
33+ int fftsToProcess = ( newAudio . Count - settings . FftSize ) / settings . StepSize ;
34+ if ( fftsToProcess < 1 )
35+ return ;
3336
34- for ( int newFftIndex = 0 ; newFftIndex < fftsToProcess ; newFftIndex ++ )
37+ double [ ] [ ] newFfts = new double [ fftsToProcess ] [ ] ;
38+
39+ Parallel . For ( 0 , fftsToProcess , newFftIndex =>
3540 {
36- // copy audio into complex buffer
37- Complex [ ] buffer = new Complex [ settings . WindowSize ] ;
41+ Complex [ ] buffer = new Complex [ settings . FftSize ] ;
3842 int sourceIndex = newFftIndex * settings . StepSize ;
39- for ( int i = 0 ; i < settings . WindowSize ; i ++ )
40- buffer [ i ] = new Complex ( newAudio [ sourceIndex ] * settings . Window [ i ] , 0 ) ;
43+ for ( int i = 0 ; i < settings . FftSize ; i ++ )
44+ buffer [ i ] = new Complex ( newAudio [ sourceIndex + i ] * settings . Window [ i ] , 0 ) ;
4145
42- // perform FFT
43- Console . WriteLine ( buffer [ 100 ] ) ;
4446 FftSharp . Transform . FFT ( buffer ) ;
4547
46- // get magnitude just from the region of interest
47- var newFft = new double [ settings . Height ] ;
48+ newFfts [ newFftIndex ] = new double [ settings . Height ] ;
4849 for ( int i = 0 ; i < settings . Height ; i ++ )
49- newFft [ i ] = buffer [ settings . FftIndex1 + i ] . Magnitude ;
50+ newFfts [ newFftIndex ] [ i ] = buffer [ settings . FftIndex1 + i ] . Magnitude / settings . FftSize ;
51+ } ) ;
52+
53+ foreach ( var newFft in newFfts )
5054 ffts . Add ( newFft ) ;
51- }
55+
56+ newAudio . RemoveRange ( 0 , fftsToProcess * settings . StepSize ) ;
5257 }
5358
5459 public Bitmap GetBitmap ( )
0 commit comments