Advertisement
Guest User

Raspberry Pi + MPD + KissFFT Spectrum Analyser

a guest
Feb 14th, 2013
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.87 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include <math.h>
  5. #include "kiss_fft.h"
  6.  
  7. float hanningWindow(short in, size_t i, size_t s) {
  8.     return in*0.5f*(1.0f-cos(2.0f*M_PI*(float)(i)/(float)(s-1.0f)));
  9. }
  10.  
  11. void drawBar(kiss_fft_cpx *fin, int start, int range) {
  12.     unsigned int i, barlen, barval;
  13.     kiss_fft_cpx ffto;
  14.    
  15.     barlen = 0;
  16.     for(i=0;i<range;i++) {
  17.         ffto = fin[start + i];
  18.        
  19.         // sqrt(i*i + r*r)
  20.         barval = sqrt(ffto.i * ffto.i + ffto.r * ffto.r);
  21.  
  22.         // 20 * log10(2^16) should max at 96(db), but i get values over 150?
  23.         barval = (unsigned int)(20.0f * (float)log10(barval));
  24.        
  25.         // Record the maximum bin value over this range
  26.         if(barval > barlen)
  27.             barlen = barval;
  28.     }
  29.    
  30.     // Generate bars 150 chars long, pad with spaces
  31.     for(i=0;i<barlen;i++)
  32.         printf("*");
  33.    
  34.     for(;i<150;i++)
  35.         printf(" ");
  36.    
  37.     printf("\n");
  38. }
  39.  
  40. int main() {
  41.     kiss_fft_cpx *fin = malloc(sizeof(kiss_fft_cpx)*1024);
  42.     kiss_fft_cpx *fout = malloc(sizeof(kiss_fft_cpx)*1024);
  43.     unsigned int barlen, barval;
  44.     int16_t buf[1024];
  45.     int fd;
  46.     int i;
  47.    
  48.    
  49.     fd = open("/tmp/mpd.fifo", O_RDONLY);   // 44100:16:1
  50.     kiss_fft_cfg mycfg = kiss_fft_alloc(1024,0,NULL,NULL);  // 1024 bins = 48kHz
  51.     printf("\033[2J");  // Clear screen
  52.    
  53.     while(read(fd, buf, sizeof(buf)) > 0) { // Keep looping while we have samples
  54.         for(i=0;i<1024;i++) {   // Populate sample buffer
  55.             fin[i].r = hanningWindow(buf[i],i,1024);    // Apply Hanning Window
  56.             fin[i].i = 0;
  57.         }
  58.  
  59.         kiss_fft(mycfg, fin, fout); // Perform FFT
  60.        
  61.         printf("\033[H");   // Return cursor to 0,0
  62.        
  63.         // Ignore the first 5 bins (DC + <200Hz)
  64.         for(i=5;i<=37;i++) {    // Pull the next 32 bins into bars
  65.             drawBar(fout, i, 1);    // Draw bars of 1 bin width
  66.         }
  67.        
  68.         for(i=3;i<24;i++) { // Generate 21 more bars from the remaining 336 bins
  69.             drawBar(fout, i*16, 16);    // Draw bars of 16 bin widths
  70.         }
  71.     }
  72.    
  73.     close(fd);
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement