문제

package soundTest;

import java.applet.*;
import java.net.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.io.*;
import java.util.*;

public class SoundTest {

public static void main(String[] args) throws Exception {

    try {
        AudioClip clip1 = Applet.newAudioClip(new URL(new File("E0.wav").getAbsolutePath())); 
        clip1.play();
    } catch (MalformedURLException murle) {
        System.out.println(murle);
    }

    URL url = new URL(
            "http://www.mediafire.com/listen/tok9j9s1hnogj1y/downloads/E0.wav"); 
    Clip clip = AudioSystem.getClip();
    AudioInputStream ais = AudioSystem.getAudioInputStream(url);
    clip.open(ais);

    URL url2 = new URL(
            "http://www.villagegeek.com/downloads/webwavs/Austin_Powers_death.wav");
    Clip clip2 = AudioSystem.getClip();
    AudioInputStream ais2 = AudioSystem.
            getAudioInputStream(url2);
    clip2.open(ais2);
    clip.loop(1);
    clip2.loop(Clip.LOOP_CONTINUOUSLY);

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JOptionPane.showMessageDialog(null, "Close to exit!");
        }
    });
}

}

I can't figure out how to play a wav file from my computer (not from a URL) in java. I'm sure that I have it placed in the right area, the SRC (I also placed it in practically every other space just in case...).

The first attempt is from http://www.cs.cmu.edu/~illah/CLASSDOCS/javasound.pdf It gives the me the catch statement.

The second attempt was putting my recorded .wav file on mediafire. However, that didn't work. "Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input URL"

The third example works fine, but, unlike my file, it's a file from online. When you click on that one, it brings you to just an audio player, while the mediafire link brings you to a page with other stuff and some application that plays the file.

도움이 되었습니까?

해결책

First Attempt

AudioClip clip1 = Applet.newAudioClip(new URL(new File("E0.wav").getAbsolutePath())); 

This is not how you construct a URL to a File. Instead, you should use File#getURI#getURL

AudioClip clip1 = Applet.newAudioClip(new File("/full/path/to/audio.wav").toURI().toURL());

Second Attempt

mediafire is returning a html response, not the audio file...You can test it with...

URL url = new URL("http://www.mediafire.com/listen/tok9j9s1hnogj1y/downloads/E0.wav");    
try (InputStream is = url.openStream()) {
    int in = -1;
    while ((in = is.read()) != -1) {
        System.out.print((char)in);
    }
} catch (IOException exp) {
    exp.printStackTrace();
}

Third Attempt

You open the clip, but never start it...

URL url2 = new URL("http://www.villagegeek.com/downloads/webwavs/Austin_Powers_death.wav");
Clip clip2 = AudioSystem.getClip();
AudioInputStream ais2 = AudioSystem.getAudioInputStream(url2);
clip2.open(ais2);
clip2.start();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top