我想能夠在我的程序中播放聲音文件。我應該在哪裏看?如何在Java中播放聲音?
回答
我寫了下面的代碼工作正常。但我認爲它只適用於.wav
格式。
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
// The wrapper thread is unnecessary, unless it blocks on the
// Clip finishing; see comments.
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
了一個壞榜樣:
import sun.audio.*; //import the sun.audio package
import java.io.*;
//** add this into your application code as appropriate
// Open an input stream to the audio file.
InputStream in = new FileInputStream(Filename);
// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);
// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);
// Similarly, to stop the audio.
AudioPlayer.player.stop(as);
http://java.sun.com/products/jdk/faq/faq-sun-packages.html有使用sun.audio的公共API替代品 – McDowell 2009-04-23 13:44:06
@GregHurlman不是太陽。 *包使我們的開發人員不使用? – 2010-06-10 14:00:07
@Tom - 可能;我通常不會發現自己使用這種代碼 – 2010-06-12 17:49:36
Java教程的Sound Trail值得成爲起點。
還有一種替代方法可以導入可在applet和應用程序中工作的聲音文件:將音頻文件轉換爲.java文件並在代碼中簡單地使用它們。
我開發了一個工具,使這個過程變得更容易。它相當簡化了Java Sound API。
我創建了一個遊戲框架較早前對Android和桌面,可處理聲音也許可以作爲靈感,你所需要的桌面部分的工作。
下面是參考代碼。
package com.athanazio.jaga.desktop.sound;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
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;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Sound {
AudioInputStream in;
AudioFormat decodedFormat;
AudioInputStream din;
AudioFormat baseFormat;
SourceDataLine line;
private boolean loop;
private BufferedInputStream stream;
// private ByteArrayInputStream stream;
/**
* recreate the stream
*
*/
public void reset() {
try {
stream.reset();
in = AudioSystem.getAudioInputStream(stream);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
line = getLine(decodedFormat);
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
line.close();
din.close();
in.close();
} catch (IOException e) {
}
}
Sound(String filename, boolean loop) {
this(filename);
this.loop = loop;
}
Sound(String filename) {
this.loop = false;
try {
InputStream raw = Object.class.getResourceAsStream(filename);
stream = new BufferedInputStream(raw);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// byte[] buffer = new byte[1024];
// int read = raw.read(buffer);
// while(read > 0) {
// out.write(buffer, 0, read);
// read = raw.read(buffer);
// }
// stream = new ByteArrayInputStream(out.toByteArray());
in = AudioSystem.getAudioInputStream(stream);
din = null;
if (in != null) {
baseFormat = in.getFormat();
decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, baseFormat
.getSampleRate(), 16, baseFormat.getChannels(),
baseFormat.getChannels() * 2, baseFormat
.getSampleRate(), false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
line = getLine(decodedFormat);
}
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
private SourceDataLine getLine(AudioFormat audioFormat)
throws LineUnavailableException {
SourceDataLine res = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
res = (SourceDataLine) AudioSystem.getLine(info);
res.open(audioFormat);
return res;
}
public void play() {
try {
boolean firstTime = true;
while (firstTime || loop) {
firstTime = false;
byte[] data = new byte[4096];
if (line != null) {
line.start();
int nBytesRead = 0;
while (nBytesRead != -1) {
nBytesRead = din.read(data, 0, data.length);
if (nBytesRead != -1)
line.write(data, 0, nBytesRead);
}
line.drain();
line.stop();
line.close();
reset();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
對於在java中播放聲音,您可以參考以下代碼。
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 {
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("gameover.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();
}
}
我不想有太多的代碼行來玩一個簡單的該死的聲音。這可以工作,如果你有JavaFX包(已經包含在我的jdk 8中)。
private static void playSound(String sound){
// cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
URL file = cl.getResource(sound);
final Media media = new Media(file.toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
注意:您需要登錄initialize JavaFX。一個快速的方法來做到這一點,是調用JFXPanel的構造函數()曾經在您的應用程序:
static{
JFXPanel fxPanel = new JFXPanel();
}
無論出於何種原因,通過wchargin最多的回答是給我一個空指針錯誤我打電話這個時候。的getClass()。的getResourceAsStream()。
什麼工作對我來說是以下幾點:
void playSound(String soundFile) {
File f = new File("./" + soundFile);
audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
}
而且我會用播放聲音:
playSound("sounds/effects/sheep1.wav");
聲音/效果/ sheep1.wav位於在我的項目的基本目錄在Eclipse中(因此不在src文件夾中)。
此線程相當老,但我確定了一個可能證明有用的選項。
除了使用Java AudioStream
庫之外,您可以使用Windows Media Player或VLC等外部程序,並通過Java命令通過控制檯命令運行它。
String command = "\"C:/Program Files (x86)/Windows Media Player/wmplayer.exe\" \"C:/song.mp3\"";
try {
Process p = Runtime.getRuntime().exec(command);
catch (IOException e) {
e.printStackTrace();
}
這也將創建一個單獨的過程,可以控制它的程序。
p.destroy();
當然,這將花費更長的時間比使用內部庫來執行,但有可能是能夠更快,並可能啓動時不給予一定的控制檯命令的GUI程序。
如果時間不是本質,那麼這很有用。
- 1. 在java中播放聲音
- 2. 錯誤在播放聲音在Java中
- 3. 如何使用java播放聲音
- 4. 的Java如何播放聲音
- 5. 聲音播放和播放聲音
- 6. 如何在Java中以指定音量播放聲音?
- 7. Java:多次播放聲音
- 8. 在Java中播放聲音文件
- 9. 不能在Java中播放聲音
- 10. 在Java程序中聲音播放
- 11. 在Java中播放聲音7
- 12. 在Java遊戲中播放小聲音
- 13. 如何在WinForms中播放聲音?
- 14. 如何在Python中播放聲音?
- 15. 如何在C++中播放.WAV聲音
- 16. 如何在WPF中播放聲音?
- 17. 如何在C#中播放聲音?
- 18. 如何在Flixel中播放wav聲音?
- 19. 如何在C#中播放聲音?
- 20. 如何在Android中播放聲音
- 21. 如何在JavaFX中播放聲音?
- 22. 如何在WPF中播放聲音
- 23. 如何在C#中播放聲音,.NET
- 24. 如何在iOS中播放聲音?
- 25. 如何在NETCore中播放聲音?
- 26. 在播放聲音
- 27. 播放聲音在
- 28. 如何從聲音的開始播放/暫停聲音和聲音播放?
- 29. 在firemonkey中播放聲音
- 30. 在C++中播放聲音
看看這個類:https://github.com/dberm22/DBoard/blob/master/src/com/dberm22/utils/MediaPlayer.java你可以調用它(新線程(new MediaPlayer(PATHTOFILE) ))。start(); – dberm22 2014-01-20 14:36:01