0

这是我第一次尝试在我的代码中使用一首歌。我一直在关注一个解释如何播放歌曲的网页(http://www3.ntu.edu.sg/home/ehchua/programming/java/J8c_PlayingSound.html),但我遇到了错误 ava.lang.IllegalArgumentException:无效的格式。我不明白为什么会发生这种情况以及我可以做些什么来播放歌曲。

这是不起作用的代码:

 private void startMusic() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        // from a wave File
        File soundFile = new File("/home/simone/OhHa/Pakman02/src/main/java/Pakman/ArsenioLupin.wav");
        AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
        Clip clip = AudioSystem.getClip();
        clip.open(audioIn);
// For small-size file only. Do not use this to open a large file over slow network, as it blocks.
        // start()
        clip.start();  // play once
// Loop()
//        clip.loop(0);  // repeat none (play once), can be used in place of start().
//        clip.loop(5);  // repeat 5 times (play 6 times)
        clip.loop(Clip.LOOP_CONTINUOUSLY);  // repeat forever
    }

有什么建议么?

4

1 回答 1

1

尝试这个。注意 javax.sound.sampled.* 的导入

 import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;

public class SoundClipTest extends JFrame {

// Constructor
public SoundClipTest() {
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setTitle("Test Sound Clip");
  this.setSize(300, 200);
  this.setVisible(true);

  try {
     // Open an audio input stream.
     URL url = this.getClass().getClassLoader().getResource("/home/simone/OhHa/Pakman02/src/main/java/Pakman/ArsenioLupin.wav");
     AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
     // Get a sound clip resource.
     Clip clip = AudioSystem.getClip();
     // Open audio clip and load samples from the audio input stream.
     clip.open(audioIn);
     clip.start();
  } catch (UnsupportedAudioFileException e) {
     e.printStackTrace();
  } catch (IOException e) {
     e.printStackTrace();
  } catch (LineUnavailableException e) {
     e.printStackTrace();
  }
}

public static void main(String[] args) {
   new SoundClipTest();
}
}

另一种选择是

import javax.swing.*;
import sun.audio.*;
import java.awt.event.*;
import java.io.*;
public class Sound {
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(200,200);
JButton button = new JButton("Click me");
frame.add(button);
button.addActionListener(new AL());
frame.show(true);
}
public static class AL implements ActionListener{
public final void actionPerformed(ActionEvent e){
music();
}
}
public static void music(){
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop = null;
try{
BGM = new AudioStream(new FileInputStream("C:\home\simone\OhHa\Pakman02\src\main\java\Pakman\ArsenioLupin.wav"));
MD = BGM.getData();
loop = new ContinuousAudioDataStream(MD);
}catch(IOException error){
System.out.print("file not found");
}
MGP.start(loop);
}
}
于 2013-01-24T09:19:14.987 回答