Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I do not get much chance to play with the sound capabilities of Java so I'm using your question as a learning exercise (I hope you don't mind). The article that you referenced about <a href="http://computermusicblog.com/blog/2008/08/29/reading-and-writing-wav-files-in-java/" rel="nofollow">Reading and Writing WAV Files in Java</a> is very old in relation to Java history (1998). Also something about constructing the WAV header by hand didn't sit quite right with me (it seemed a little error prone). As Java is quite a mature language now I would expect library support for this kind of thing.</p> <p>I was able to construct a WAV file from a byte array by hunting around the internet for sample code snippets. This is the code that I came up with (I expect it is sub-optimal but it seems to work):</p> <pre><code>// Generate bang noise data // Sourced from http://www.rgagnon.com/javadetails/java-0632.html public static byte[] bang() { byte[] buf = new byte[8050]; Random r = new Random(); boolean silence = true; for (int i = 0; i &lt; 8000; i++) { while (r.nextInt() % 10 != 0) { buf[i] = silence ? 0 : (byte) Math.abs(r.nextInt() % (int) (1. + 63. * (1. + Math.cos(((double) i) * Math.PI / 8000.)))); i++; } silence = !silence; } return buf; } private static void save(byte[] data, String filename) throws IOException, LineUnavailableException, UnsupportedAudioFileException { InputStream byteArray = new ByteArrayInputStream(data); AudioInputStream ais = new AudioInputStream(byteArray, getAudioFormat(), (long) data.length); AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename)); } private static AudioFormat getAudioFormat() { return new AudioFormat( 8000f, // sampleRate 8, // sampleSizeInBits 1, // channels true, // signed false); // bigEndian } public static void main(String[] args) throws Exception { byte[] data = bang(); save(data, "test.wav"); } </code></pre> <p>I hope it helps.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload