2010-03-10 28 views
41

Tôi đang cố gắng phát tệp * .wav bằng Java. Tôi muốn thực hiện như sau:
Khi nhấn một nút, phát một âm thanh tiếng bíp ngắn.Cách phát tệp .wav với java

Tôi đã googled nó, nhưng hầu hết mã không hoạt động. Ai đó có thể cho tôi một đoạn mã đơn giản để phát tệp .wav không?

+0

những gì đã không làm việc và tại sao – Bozho

Trả lời

32

Cuối cùng tôi quản lý để làm như sau và nó hoạt động tốt

import java.io.File; 
import java.io.IOException; 

import javax.sound.sampled.AudioFormat; 
import javax.sound.sampled.AudioInputStream; 
import javax.sound.sampled.AudioSystem; 
import javax.sound.sampled.DataLine; 
import javax.sound.sampled.LineUnavailableException; 
import javax.sound.sampled.SourceDataLine; 

public class MakeSound { 

    private final int BUFFER_SIZE = 128000; 
    private File soundFile; 
    private AudioInputStream audioStream; 
    private AudioFormat audioFormat; 
    private SourceDataLine sourceLine; 

    /** 
    * @param filename the name of the file that is going to be played 
    */ 
    public void playSound(String filename){ 

     String strFilename = filename; 

     try { 
      soundFile = new File(strFilename); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      System.exit(1); 
     } 

     try { 
      audioStream = AudioSystem.getAudioInputStream(soundFile); 
     } catch (Exception e){ 
      e.printStackTrace(); 
      System.exit(1); 
     } 

     audioFormat = audioStream.getFormat(); 

     DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); 
     try { 
      sourceLine = (SourceDataLine) AudioSystem.getLine(info); 
      sourceLine.open(audioFormat); 
     } catch (LineUnavailableException e) { 
      e.printStackTrace(); 
      System.exit(1); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      System.exit(1); 
     } 

     sourceLine.start(); 

     int nBytesRead = 0; 
     byte[] abData = new byte[BUFFER_SIZE]; 
     while (nBytesRead != -1) { 
      try { 
       nBytesRead = audioStream.read(abData, 0, abData.length); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      if (nBytesRead >= 0) { 
       @SuppressWarnings("unused") 
       int nBytesWritten = sourceLine.write(abData, 0, nBytesRead); 
      } 
     } 

     sourceLine.drain(); 
     sourceLine.close(); 
    } 
} 
+9

Điều này không phù hợp với tôi. Tôi khuyên bạn nên sử dụng một cách rất đơn giản: [http://alvinalexander.com/java/java-audio-example-java-au-play-sound](http://alvinalexander.com/java/java-audio-example-java -au-play-sound) – duleshi

+8

Nghiêm túc nếu đây là những gì cần thiết để chơi một âm thanh wav trong Java thì tôi sẽ ngừng sử dụng Java, may mắn thay tôi nghi ngờ điều này là đúng. –

+0

@duleshi ví dụ của bạn làm việc cho tôi và nó thật đơn giản :) –

3

Đoạn here hoạt động tốt, thử nghiệm với cửa sổ cách âm:

public static void main(String[] args) { 
     AePlayWave aw = new AePlayWave("C:\\WINDOWS\\Media\\tada.wav"); 
     aw.start();  
} 
+0

Nếu bạn vẫn còn có vấn đề với điều đó cố gắng thay đổi các thiết bị âm thanh. Xem thêm công cụ được đề xuất ở đây http://stackoverflow.com/questions/2175318/how-to-change-default-sound-playback-device-programatically/2216886#2216886 – stacker

25

Dưới đây là hình thức thanh lịch nhất mà tôi có thể đến lên mà không sử dụng mặt trời. *:

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

try { 
    File yourFile; 
    AudioInputStream stream; 
    AudioFormat format; 
    DataLine.Info info; 
    Clip clip; 

    stream = AudioSystem.getAudioInputStream(yourFile); 
    format = stream.getFormat(); 
    info = new DataLine.Info(Clip.class, format); 
    clip = (Clip) AudioSystem.getLine(info); 
    clip.open(stream); 
    clip.start(); 
} 
catch (Exception e) { 
    //whatevers 
} 
+1

Tôi không thể nghe thấy bất kỳ âm thanh nào phát ra bằng cách sử dụng mã mẫu này. Có điều gì tôi đang bỏ lỡ không? –

+1

Nó nên được hoàn thành, nhưng nó cũng là năm tuổi, và xấu xí. Tôi chắc chắn có những cách làm đẹp hơn, sử dụng các thư viện Java tốt. – tschwab

+1

Để nghe đầu ra, bạn nên trì hoãn việc chấm dứt ứng dụng trong thời gian phát lại. Thử đặt 'Thread.sleep (1000)' sau 'clip.start()'. – Metaphore

15

Ngắn nhất hình thức (mà không cần phải cài đặt các thư viện ngẫu nhiên)?

public static void play(String filename) 
{ 
    try 
    { 
     Clip clip = AudioSystem.getClip(); 
     clip.open(AudioSystem.getAudioInputStream(new File(filename))); 
     clip.start(); 
    } 
    catch (Exception exc) 
    { 
     exc.printStackTrace(System.out); 
    } 
} 

Vấn đề duy nhất là không có cách nào tốt để làm cho phương pháp chặn này đóng và hủy bỏ dữ liệu sau khi * .wav kết thúc. clip.drain() cho biết nó đang chặn nhưng không. Đoạn clip không hoạt động QUYỀN SAUstart(). Các chỉ làm việc nhưng xấu xí cách tôi tìm thấy là:

// ... 
clip.start(); 
while (!clip.isRunning()) 
    Thread.sleep(10); 
while (clip.isRunning()) 
    Thread.sleep(10); 
clip.close(); 
+5

clip có 'addLineListener', do đó bạn không cần sử dụng vòng lặp' while' ... –

10

Bạn có thể sử dụng một người biết lắng nghe sự kiện để đóng clip sau khi nó được chơi

import java.io.File; 
import javax.sound.sampled.*; 

public void play(File file) 
{ 
    try 
    { 
     final Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class)); 

     clip.addLineListener(new LineListener() 
     { 
      @Override 
      public void update(LineEvent event) 
      { 
       if (event.getType() == LineEvent.Type.STOP) 
        clip.close(); 
      } 
     }); 

     clip.open(AudioSystem.getAudioInputStream(file)); 
     clip.start(); 
    } 
    catch (Exception exc) 
    { 
     exc.printStackTrace(System.out); 
    } 
} 
+0

Đổi tên bạn có thể thêm sau khi bắt đầu câu "clip.drain()" nếu bạn muốn đợi cho đến khi luồng âm thanh được xử lý bởi Line. – Victor

0

Một cách khác để làm việc đó với AudioInputStream:

import java.io.File; 

import javax.sound.sampled.AudioInputStream; 
import javax.sound.sampled.AudioSystem; 
import javax.sound.sampled.Clip; 
import javax.sound.sampled.Line; 
import javax.sound.sampled.LineEvent; 
import javax.sound.sampled.LineListener; 
import javax.swing.JDialog; 
import javax.swing.JFileChooser; 

public class CoreJavaSound extends Object implements LineListener { 
    File soundFile; 

    JDialog playingDialog; 

    Clip clip; 

    public static void main(String[] args) throws Exception { 
     CoreJavaSound s = new CoreJavaSound(); 
    } 

    public CoreJavaSound() throws Exception { 
     JFileChooser chooser = new JFileChooser(); 
     chooser.showOpenDialog(null); 
     soundFile = chooser.getSelectedFile(); 

     System.out.println("Playing " + soundFile.getName()); 

     Line.Info linfo = new Line.Info(Clip.class); 
     Line line = AudioSystem.getLine(linfo); 
     clip = (Clip) line; 
     clip.addLineListener(this); 
     AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile); 
     clip.open(ais); 
     clip.start(); 
    } 

    public void update(LineEvent le) { 
     LineEvent.Type type = le.getType(); 
     if (type == LineEvent.Type.OPEN) { 
      System.out.println("OPEN"); 
     } else if (type == LineEvent.Type.CLOSE) { 
      System.out.println("CLOSE"); 
      System.exit(0); 
     } else if (type == LineEvent.Type.START) { 
      System.out.println("START"); 
      playingDialog.setVisible(true); 
     } else if (type == LineEvent.Type.STOP) { 
      System.out.println("STOP"); 
      playingDialog.setVisible(false); 
      clip.close(); 
     } 
    } 
} 
1

Lớp học sẽ phát tệp WAV, chặn cho đến khi phát xong âm thanh:

class Sound implements Playable { 

    private final Path wavPath; 
    private final CyclicBarrier barrier = new CyclicBarrier(2); 

    Sound(final Path wavPath) { 

     this.wavPath = wavPath; 
    } 

    @Override 
    public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException { 

     try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile()); 
      final Clip clip = AudioSystem.getClip()) { 

      listenForEndOf(clip); 
      clip.open(audioIn); 
      clip.start(); 
      waitForSoundEnd(); 
     } 
    } 

    private void listenForEndOf(final Clip clip) { 

     clip.addLineListener(event -> { 
      if (event.getType() == LineEvent.Type.STOP) waitOnBarrier(); 
     }); 
    } 

    private void waitOnBarrier() { 

     try { 

      barrier.await(); 
     } catch (final InterruptedException ignored) { 
     } catch (final BrokenBarrierException e) { 

      throw new RuntimeException(e); 
     } 
    } 

    private void waitForSoundEnd() { 

     waitOnBarrier(); 
    } 
} 
0

Bạn có thể sử dụng dòng âm thanh theo cách này cũng như:

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

import sun.audio.AudioPlayer; 
import sun.audio.AudioStream; 

public class AudioWizz extends JPanel implements ActionListener { 

    private static final long serialVersionUID = 1L; //you like your cereal and the program likes their "serial" 

    static AudioWizz a; 
    static JButton playBuddon; 
    static JFrame frame; 

    public static void main(String arguments[]){ 

     frame= new JFrame("AudioWizz"); 
     frame.setSize(300,300); 
     frame.setVisible(true); 
     a= new AudioWizz(); 
     playBuddon= new JButton("PUSH ME"); 
     playBuddon.setBounds(10,10,80,30); 
     playBuddon.addActionListener(a); 

     frame.add(playBuddon); 
     frame.add(a); 
    } 

    public void actionPerformed(ActionEvent e){ //an eventListener 
     if (e.getSource() == playBuddon) { 
      try { 
       InputStream in = new FileInputStream("*.wav"); 
       AudioStream sound = new AudioStream(in); 
       AudioPlayer.player.start(sound); 
      } catch(FileNotFoundException e1) { 
       e1.printStackTrace(); 
      } catch (IOException e1) { 
       e1.printStackTrace(); 
      } 
     } 
    } 

} 
1

một giải pháp mà không java phản ánh DataLine.Info info = new DataLine.Info (SourceDataLine.class, audioFormat); phản chiếu java giảm hiệu suất. để chạy: java PlaySound absoluteFilePathTo/file.wav

import javax.sound.sampled.*; 
import java.io.*; 
public class playsound 
{ 
    public static void main (String args[]) throws Exception 
    { 
     playSound (args [0]); 
    } 
    public static 
    void playSound 
    ( 
     String filename 
    ) throws Exception 
    { 

     AudioInputStream 
     audioStream = 
     AudioSystem.getAudioInputStream 
     (new File (filename)); 

     int BUFFER_SIZE = 128000; 
     AudioFormat audioFormat = null; 
     SourceDataLine sourceLine = null; 

     audioFormat = audioStream.getFormat(); 

     sourceLine = (SourceDataLine) 
     AudioSystem.getSourceDataLine 
     (audioFormat); 

     sourceLine.open (audioFormat); 

     sourceLine.start(); 

     int nBytesRead = 0; 
     byte[] abData = new byte[BUFFER_SIZE]; 
     while (nBytesRead != -1) 
     { 
      try 
      { 
       nBytesRead = 
       audioStream.read 
       (abData, 0, abData.length); 
      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 
      if (nBytesRead >= 0) 
      { 
       int nBytesWritten = 
       sourceLine.write 
       (abData, 0, nBytesRead); 
      } 
     } 

     sourceLine.drain(); 
     sourceLine.close(); 
    } 

} 
Các vấn đề liên quan