2013-08-08

Playing wav files with Java, no errors, but also no sound

I was trying to play a wav file using an old Java API. It was relatively straightforward. Upon running to code, there were no run time exceptions thrown. However, the play() call also did not result in any sound being produced. I then searched around for possible reasons. One possible reason is that the wav file format supports a number of different audio codecs (not just PCM). Please refer http://en.wikipedia.org/wiki/WAV#WAV_file_compression_codecs_compared to for the list. However, java only supports a smaller subset of this (PCM, ADPCM formats). If you have a wav file that is has MP3 as the codec you would have to reexport the file out from your sound editor as a PCM encoded wav file. I used a open source audio sound editor named Audacity. http://audacity.sourceforge.net/. In may case, the wav file I had required that I download the MP3 codec it libraries to decode it. The option to download the library could be found in edit>preferences>libraries. Import the wav (mp3 encoded) and then reexport (defaults to PCM) to another wav file as PCM encoded.



JavaSounds.java
 1 package example;
 2 
 3 import java.applet.*;
 4 import java.awt.event.ActionEvent;
 5 import java.awt.event.ActionListener;
 6 import java.net.*;
 7 import javax.swing.*;
 8 
 9 public class JavaSounds {
10 
11     public static void playsound(String name) {
12         try {
13             AudioClip clip = Applet.newAudioClip(new URL(name));
14             clip.play();
15         } catch (Exception e){ 
16             System.out.println("An error occured, please try again..."); 
17         }
18     }
19     
20 
21     public static void main(String[] args) {
22         JFrame f = new JFrame("Sounds Example");
23         JButton btn = new JButton("Clang");
24         f.add(btn);
25         f.setSize(200, 100);
26         f.setLocationRelativeTo(null);
27         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
28         // use anonymous inner function to handle event 
29         btn.addActionListener(new ActionListener() {
30             public void actionPerformed(ActionEvent event) {
31                 playsound("file:coin.wav");
32             }
33         });
34 
35         f.setVisible(true);
36     }
37 }
38 

No comments:

Post a Comment

Github CoPilot Alternatives (VSCode extensions)

https://www.tabnine.com/blog/github-copilot-alternatives/