Guest User

from https://www.commandlinefu.com/commands/using/aplay

a guest
Jul 23rd, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.42 KB | None | 0 0
  1. // run.sh
  2. #!/bin/bash
  3.  
  4. gcc -x c main.c
  5.  
  6. # aplay's -d option specifies duration. So even though main.c
  7. # is an infinite loop, it'll kill it after 2 seconds.
  8. ./a.out < /dev/urandom | aplay -d 4
  9.  
  10. // main.c
  11. #include <unistd.h>
  12. #include <stdio.h>
  13. #include <stdint.h>
  14.  
  15. #define FREQ 220
  16.  
  17. // 16000 = 16khz comes from the duration (2 seconds).
  18. // Note that aplay will eat bytes at 8khz by default.
  19. // This means if FREQ = 1, it's just outputing from /dev/urandom.
  20.  
  21. // Probably gets 220 from here: https://en.wikipedia.org/wiki/Piano_key_frequencies
  22. int size = 16000/FREQ;
  23.  
  24. void main(){
  25.    int i = 0;
  26.    uint8_t v[size];
  27.    read(STDIN_FILENO,v,size); // write "size" bytes from stdin to v.
  28.    
  29.    // v now contains random data.
  30.    
  31.    while(1){
  32.       // This algorithm basically averages out the random buffer.
  33.       // Over time, it'll reach a steady state (this produces the fade out effect).
  34.       // How long this takes depends on "size".
  35.       // size = O(1/FREQ), and a large buffer takes longer to reach steady state.
  36.       // this is because freq = 1/wavelength, so our random buffer represents our wave. (I THINK.)
  37.      
  38.       // Notice that we don't have to generate some kind of sine wave.
  39.  
  40.       // This sets the index BEFORE the one we output.
  41.       // So the first run outputs directly from /dev/urandom.
  42.       v[i%size] = (v[i%size]+v[++i%size]) / 2;
  43.      
  44.       putchar(v[i%size]);
  45.    }
  46.    
  47. }
Add Comment
Please, Sign In to add comment