Glimmer

Faint insights into (mostly) the world of automation

Java Sound Update

| Comments

For years, I have been using (and advising the use of sun.audio) for playing sounds in the Java VM using Alvin Alexander’s article for inspiration. The downside of this approach, of course, is the dependency on classes that are not part of the JAVA API and therefore might change at anytime although they have been relatively stable for many years.

Recently, I found a stackoverflow discussion noting the existence of AudioSystem (and related clases).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
 * File: ModernRingPhone.java
 * Author: David Green <dgreen@uab.edu>
 * Assignment:  SoundOff - EE333 Fall 2014
 * Vers: 1.0.0 10/23/2014 dgg - initial coding
 *
 * Credits:  Concepts from http://stackoverflow.com/questions/15475276/short-sound-file-plays-in-netbeans-but-not-in-jar
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

/**
 *
 * @author David Green <dgreen@uab.edu>
 */
public class ModernRingPhone {

  public static void main(String[] args)
  {
    try {
        // open the sound file as a Java input stream
        String gongFile = "telephone-ring-3.wav";

        // create an audiostream from the inputstream
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(new File(gongFile)));

        // play the audio clip with the audioplayer class
        clip.start();

        // wait for sound to finish before terminating program (necessary for 
        // running inside NetBeans, at least)
        Thread.sleep(10000);
    }
    catch ( Exception e) {
        System.out.println("Things did not go well" );
        e.printStackTrace();
        System.exit(-1);
    }
  }
}

Update: 2015-02-08 Removed unnecessary line of code

Update: 2015-12-10 Revised example is available here.

Comments