[英]Playing .mp3 and .wav in Java?
如何在我的 Java 應用程序中播放.mp3
和.wav
文件? 我正在使用 Swing。 我嘗試在互聯網上查找類似以下示例的內容:
public void playSound() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:/MusicPlayer/fml.mp3").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
但是,這只會播放.wav
文件。
與以下相同:
http://www.javaworld.com/javaworld/javatips/jw-javatip24.html
我希望能夠使用相同的方法播放.mp3
文件和.wav
文件。
Java FX 具有播放 mp3 文件的Media
和MediaPlayer
類。
示例代碼:
String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
您將需要以下導入語句:
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
我寫了一個純 java mp3 播放器: mp3transform 。
使用標准的 javax.sound API、單個 Maven 依賴項、完全開源(需要Java 7或更高版本),這應該能夠播放大多數 WAV、OGG Vorbis 和 MP3 文件:
pom.xml :
<!--
We have to explicitly instruct Maven to use tritonus-share 0.3.7-2
and NOT 0.3.7-1, otherwise vorbisspi won't work.
-->
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>tritonus-share</artifactId>
<version>0.3.7-2</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>mp3spi</artifactId>
<version>1.9.5-1</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>vorbisspi</artifactId>
<version>1.0.3-1</version>
</dependency>
代碼:
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.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;
public class AudioFilePlayer {
public static void main(String[] args) {
final AudioFilePlayer player = new AudioFilePlayer ();
player.play("something.mp3");
player.play("something.ogg");
}
public void play(String filePath) {
final File file = new File(filePath);
try (final AudioInputStream in = getAudioInputStream(file)) {
final AudioFormat outFormat = getOutFormat(in.getFormat());
final Info info = new Info(SourceDataLine.class, outFormat);
try (final SourceDataLine line =
(SourceDataLine) AudioSystem.getLine(info)) {
if (line != null) {
line.open(outFormat);
line.start();
stream(getAudioInputStream(outFormat, in), line);
line.drain();
line.stop();
}
}
} catch (UnsupportedAudioFileException
| LineUnavailableException
| IOException e) {
throw new IllegalStateException(e);
}
}
private AudioFormat getOutFormat(AudioFormat inFormat) {
final int ch = inFormat.getChannels();
final float rate = inFormat.getSampleRate();
return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
}
private void stream(AudioInputStream in, SourceDataLine line)
throws IOException {
final byte[] buffer = new byte[4096];
for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
line.write(buffer, 0, n);
}
}
}
參考資料:
您只能使用 Java API 播放 .wav:
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
代碼:
AudioInputStream audioIn = AudioSystem.getAudioInputStream(MyClazz.class.getResource("music.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
並使用 jLayer 播放 .mp3
我已經有一段時間沒有使用它了,但是JavaLayer非常適合 MP3 播放
我建議使用 BasicPlayerAPI。 它是開源的,非常簡單,不需要 JavaFX。 http://www.javazoom.net/jlgui/api.html
下載並解壓 zip 文件后,應將以下 jar 文件添加到項目的構建路徑中:
這是一個簡約的用法示例:
String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
player.open(new URL("file:///" + pathToMp3));
player.play();
} catch (BasicPlayerException | MalformedURLException e) {
e.printStackTrace();
}
所需的進口:
import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;
這就是您開始播放音樂所需的全部內容。 播放器正在啟動和管理自己的播放線程,並提供播放、暫停、恢復、停止和搜索功能。
對於更高級的用法,您可以查看 jlGui 音樂播放器。 這是一個開源的 WinAmp 克隆: http : //www.javazoom.net/jlgui/jlgui.html
要查看的第一個類是PlayerUI (在包 javazoom.jlgui.player.amp 內)。 它很好地展示了 BasicPlayer 的高級功能。
我發現的最簡單的方法是從http://www.javazoom.net/javalayer/sources.html下載 JLayer jar 文件並將其添加到 Jar 庫http://www.wikihow.com/Add-JARs- to-Project-Build-Paths-in-Eclipse-%28Java%29
這是類的代碼
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
} catch(Exception e){
System.out.println(e);
}
}
}
這是進口
import javazoom.jl.player.*;
import java.io.FileInputStream;
為了給讀者另一種選擇,我建議使用 JACo MP3 播放器庫,這是一個跨平台的 java mp3 播放器。
特征:
有關其方法和屬性的完整列表,您可以在此處查看其文檔。
示例代碼:
import jaco.mp3.player.MP3Player;
import java.io.File;
public class Example1 {
public static void main(String[] args) {
new MP3Player(new File("test.mp3")).play();
}
}
有關更多詳細信息,我在此處創建了一個簡單的教程,其中包含可下載的源代碼。
使用MP3 解碼器/播放器/轉換器Maven 依賴項。
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class PlayAudio{
public static void main(String[] args) throws FileNotFoundException {
try {
FileInputStream fileInputStream = new FileInputStream("mp.mp3");
Player player = new Player((fileInputStream));
player.play();
System.out.println("Song is playing");
while(true){
System.out.println(player.getPosition());
}
}catch (Exception e){
System.out.println(e);
}
}
}
您需要先安裝 JMF( 使用此鏈接下載)
File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();
不要忘記添加 JMF jar 文件
在 freshmeat.net 上搜索 JAVE(代表 Java 音頻視頻編碼器)庫(鏈接在這里)。 這是一個存放這類東西的圖書館。 不知道Java有沒有原生的mp3功能。
如果您想要一種方法來運行這兩種類型的文件,您可能需要使用繼承和簡單的包裝函數將 mp3 函數和 wav 函數包裝在一起。
我有其他方法,第一個是:
public static void playAudio(String filePath){
try{
InputStream mus = new FileInputStream(new File(filePath));
AudioStream aud = new AudioStream(mus);
}catch(Exception e){
JOptionPane.showMessageDialig(null, "You have an Error");
}
第二個是:
try{
JFXPanel x = JFXPanel();
String u = new File("021.mp3").toURI().toString();
new MediaPlayer(new Media(u)).play();
} catch(Exception e){
JOPtionPane.showMessageDialog(null, e);
}
如果我們想循環播放這個音頻,我們使用這個方法。
try{
AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
AudioPlayer.player.start(s);
} catch(Exception ex){
JOPtionPane.showMessageDialog(null, ex);
}
如果我們想停止這個循環,我們在 try 中添加這個庫:
AudioPlayer.player.stop(s);
對於這第三種方法,我們添加以下導入:
import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;
要將 MP3 讀取支持添加到 Java Sound,請將 JMF 的mp3plugin.jar
添加到應用程序的運行時類路徑。
請注意, Clip
類具有內存限制,使其不適用於幾秒鍾以上的高質量聲音。
google 並先下載 Jlayer 庫。
import javazoom.jl.player.Player;
import java.io.FileInputStream;
public class MusicPlay {
public static void main(String[] args) {
try{
FileInputStream fs = new FileInputStream("audio_file_path.mp3");
Player player = new Player(fs);
player.play();
} catch (Exception e){
// catch exceptions.
}
}
}
使用這個庫: import sun.audio.*;
public void Sound(String Path){
try{
InputStream in = new FileInputStream(new File(Path));
AudioStream audios = new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch(Exception e){}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.