2011-08-18 137 views
0

我想在java中按钮ckick上播放声音(a.mp3)。如何使用java播放声音

我想这个代码

AudioPlayer.player.start(新的FileInputStream(新文件( “E://a.mp3”)));

但声音不清晰....

我应该怎么做,(我在Java初学者)。

+1

什么是AudioPlayer类?这不是J2SE API的一部分。 – cgull

回答

0

看看JLayer。这是几年前我能找到的最好的图书馆。这不是完美的,但应该适合你的需求。

1
**For Playing sound in java, please refer to the following code.** 

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

    // To play sound using Clip, the process need to be alive. 
    // Hence, we use a Swing application. 
    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("filenamme.mp3"); 
      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(); 
     } 
    }