0

I want just to perform a simple task. (I'm a java newbie). I want to play an audio clip when a button is clicked. here's the part of my code(which I did exactly by copying a tutorial from Youtube.)

private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {                                         
InputStream in;
try{
      in=new FileInputStream(new File("C:\\Users\\Matt\\Documents\\dong.wav"));
      AudioStream timeupsound=new AudioStream(in);
      AudioPlayer.player.start(timeupsound);

}
catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}

}                                     

But the problem is, this doesn't work. It throws and IOException saying: "could not create audio stream from input stream". My question is, what am I doing wrong? (as I clearly saw this code work in that youtube video, and I've used the same code. Please help. and once again, I'm a newbie);

mattmorgan
  • 13
  • 2
  • 5
  • @Andrew, yes. You are right. It was the wav file's problem. not the code. I tested it with several wav files, and it worked for just one of them. – mattmorgan Jan 23 '14 at 14:21
  • I worked the comments into an answer that may get you further. – Andrew Thompson Jan 23 '14 at 15:53
  • I find that Java has trouble with wav files if they are not 16-bit, but 24-bit or 32-bit encoding. Another common "problem" is the byte order. Java might prefer little-endian, but I could be wrong, and Java might actually support both little- and bit-endian (but not for all encodings or rates). There are also some lower fps rates than 44100 fps that are supported, but not all that might be found. The most common hangup for me has been 24-bit and 32-bit rather than 16-bit. – Phil Freihofner Jan 26 '14 at 03:11

1 Answers1

2

The sun package classes should be causing some informative warnings at compile time. Heed them. Don't use classes in that package hierarchy. They are undocumented, are not guaranteed from one Java version to the next, and will probably not be available in a non-Oracle JRE at all.

Instead use the Java Sound based Clip to play audio. See the info. page for working examples.

Note

It might be the WAV is encoded in a format that Java Sound does not support. Media formats are typically 'container formats' that might be encoded using any number of different Codecs. It is likely that WAV is using a more compressive Codec such as MP3 or OGG internally.

I don't know of a Service Provider Interface for the OGG format, but if they are encoded as MP3, you might be able to get it working using the MP3 SPI. See the info. page linked above for details.

Tip

Also change code of the form:

catch (Exception e) { .. 

To

catch (Exception e) { 
    e.printStackTrace(); // very informative! ... 
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433