基本音訊輸出

Hello Audio! 從本地或網際網路儲存播放聲音檔案的 Java 如下所示。它適用於未壓縮的 .wav 檔案,不應用於播放 mp3 或壓縮檔案。

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

public class SoundClipTest {

   // Constructor
   public SoundClipTest() {          
      try {
         // Open an audio input stream.           
          File soundFile = new File("/usr/share/sounds/alsa/Front_Center.wav"); //you could also get the sound file with an URL
          AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile); 
          AudioFormat format = audioIn.getFormat();             
         // Get a sound clip resource.
         DataLine.Info info = new DataLine.Info(Clip.class, format);
         Clip clip = (Clip)AudioSystem.getLine(info);
         // 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();
   }
}