public static void
public static void

Reputation: 95

how do I play a wave (wav) file in java

I've looked around on stack overflow, and a few other sites, but I can't really find anything helpful. I need to have code that can play an audio file that is inside the same as my Class.java file. In other words, I need it to play a file without typing in the exact location of the file, llike if I was sending it to a friend. Here is what I have:

import java.applet.*;
import java.net.*;
public class MainClass extends Applet {

public void init() {
  try {
     AudioClip clip = Applet.newAudioClip(
                    new URL(“file://C:/sound.wav”));
     clip.play();
  } catch (MalformedURLException murle) {
  murle.printStackTrace();
}
}

But I can't get it to play from just anywhere, only that specific folder. Is there a way to do this without typing "URL" before the file location?

Upvotes: 0

Views: 3416

Answers (2)

Fevly Pallar
Fevly Pallar

Reputation: 3099

Change your URL declaration , change "file://C:/sound.wav" to "file:C:/sound.wav"

import java.applet.*;
import java.net.*;
public class MainClass {
public static void main(String[] args) {
  try {
     AudioClip clip = Applet.newAudioClip(
                    new URL("file:C:/sound.wav"));
     clip.play();
  } catch (MalformedURLException murle) {
  murle.printStackTrace();
}}}

*I had tested it and working great under NetBeans IDE

Upvotes: 1

Code-Apprentice
Code-Apprentice

Reputation: 83517

I believe Applet.audioClip() is intended for use inside Applets, rather than a desktop app. One of the limitations is that you can only use a URL to locate the sound resource. On the other hand the Java Sound API is more versatile. It allows you to locate the sound resource with a File object as well as many other options.

You also need to figure out how to refer to your file. In particular, if you want to use a relative path, you need to figure out what base path your environment will start from. Embedding resources (images, sound bits, etc) into a Java project then use those resources will give you more details about how to resolve this issue.

Upvotes: 1

Related Questions