Guest User

Untitled

a guest
May 19th, 2017
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. import java.io.FileOutputStream;
  2. import java.io.IOException;
  3. import java.nio.ByteBuffer;
  4. import java.nio.ByteOrder;
  5.  
  6. /**
  7.  * Commands to generate and play sound file:
  8.  *
  9.  *  $ avconv -f f64le -ar 44100 -ac 1 -i /tmp/snd.raw /tmp/snd.wav
  10.  *  $ mplayer /tmp/snd.wav
  11.  *  
  12.  */
  13. public class SndGen {
  14.     public static void main(String[] args) throws IOException {
  15.         double freqs[]=new double[]{440, 660, 880};
  16.         double amplitudes[]=new double[]{.5,.3,.2};
  17.         double sampleFreq=44100;
  18.         double lengthInSecs=5;
  19.         int nSample=(int)(lengthInSecs*sampleFreq);
  20.         ByteBuffer bb=ByteBuffer.allocate(8);
  21.         bb.order(ByteOrder.LITTLE_ENDIAN);
  22.         byte[] buffer=new byte[8];
  23.         try(FileOutputStream fos=new FileOutputStream("/tmp/snd.raw"))
  24.         {
  25.             for(int i=0;i<nSample;++i)
  26.             {
  27.                 double t=i*1.0/sampleFreq;
  28.                 double sample=0;
  29.                 for(int j=0;j<freqs.length;++j)
  30.                 {
  31.                     double omega=freqs[j]*2.0*Math.PI;
  32.                     sample+=amplitudes[j]*Math.sin(omega*t);
  33.                 }
  34.                 bb.clear();
  35.                 bb.putDouble(sample);
  36.                 bb.flip();
  37.                 bb.get(buffer);
  38.                 fos.write(buffer);
  39.             }
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment