Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import javax.sound.sampled.*;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.File;
  4.  
  5. public class ArrayToWavHelper {
  6. private static int sampleRate = 22050;
  7. public static void main(String[] args) throws Exception {
  8. final AudioFormat frmt = new AudioFormat(sampleRate, 8, 1, true, true);
  9. try {
  10. SourceDataLine line = AudioSystem.getSourceDataLine(frmt);
  11. line.open(frmt);
  12. line.start();
  13.  
  14. //Frequency = ... Hz for ... seconds
  15. byte[] bytes = generateSineWavefreq(50, 5);
  16.  
  17. AudioInputStream ais = new AudioInputStream(new ByteArrayInputStream(bytes), frmt, bytes.length);
  18. AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File("test.wav"));
  19.  
  20. play(line, bytes);
  21. line.drain();
  22. line.close();
  23.  
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. }
  27. }
  28.  
  29. private static byte[] generateSineWavefreq(int frequencyOfSignal, int seconds) {
  30. // total samples = (duration in second) * (samples per second)
  31. byte[] sin = new byte[seconds * sampleRate];
  32. double samplingInterval = (double) (sampleRate / frequencyOfSignal);
  33. System.out.println("Sampling Frequency : " + sampleRate);
  34. System.out.println("Frequency of Signal : " + frequencyOfSignal);
  35. System.out.println("Sampling Interval : " + samplingInterval);
  36. for (int i = 0; i < sin.length; i++) {
  37. double angle = (2.0 * Math.PI * i) / samplingInterval;
  38. sin[i] = (byte) (Math.sin(angle) * 127);
  39. System.out.println("" + sin[i]);
  40. }
  41. return sin;
  42. }
  43.  
  44. private static void play(SourceDataLine line, byte[] array) {
  45. int length = sampleRate * array.length / 1000;
  46. line.write(array, 0, array.length);
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement