2017-04-07 46 views
0

我在很多論壇和YouTube教程中搜索了一段簡單的代碼來播放聲音文件(.mp3),但是我發現的所有內容都不適用於我。如何在Java中播放聲音文件

我總是得到它找不到該文件或其他錯誤的異常,但它總是以異常結束。

有什麼我必須首先配置可能嗎?

CNC中 我再次嘗試下面的代碼,以顯示我得到了exeption:

Here is my code

加入JFXPanel我得到了exeption後:異常線程 「main」 MediaException :MEDIA_UNAVAILABLE:D:\ bip.mp3(系統無法找到文件)// 和是的,我檢查路徑是否正確。

+0

這是我搜查的第一件事http://stackoverflow.com/questions/6045384/playing-mp3-and-wav-in-java –

+1

[在Java中播放.mp3和.wav?]的可能的副本(http://stackoverflow.com/questions/6045384/playing-mp3-and-wav-in-java) –

+0

[JavaFX:「Toolkit」在嘗試通過MediaPlayer類播放mp3文件時未初始化](http://stackoverflow.com/questions/14025718/javafx-toolkit-not-initialized-when-trying-to-play-an-mp3-file-through- mediap) – phihag

回答

0

也許發佈一個特定的錯誤可以解決您的問題,但無論如何,我認爲this可以幫助你。而且我也實施了它,併爲我完美工作。

這是我如何做它:

List<Media> mediaList = new ArrayList<>(); 
FileManager files = new FileManager(); 
files.loadMediaFiles(new File("your music directory goes here..")); 

files.getFiles().stream().forEach((media) -> { 
    mediaList.add(new Media(media)); 
}); 


MediaPlayer mediaPlayer = new MediaPlayer(playList.get(0)); 
MediaView mediaView = new MediaView(mediaPlayer); 

playPauseButton.setOnAction((ActionEvent event) -> { 
     if (mediaPlayer.getStatus() == Status.PAUSED || mediaPlayer.getStatus() == Status.READY || mediaPlayer.getStatus() == Status.STOPPED) { 
      mediaPlayer.play(); 
      playPauseButton.setGraphic(pause); 
     } else { 
      mediaPlayer.pause(); 
      playPauseButton.setGraphic(play); 
     } 
    }); 

您也可以結帳我app GitHub上。

2

爲了避免初始化異常,你必須要麼調用Application.launch()方法或者乾脆實例新JFXPanel()類(即使它不用於任何東西)。這將啓動JavaFxRuntime當應用程序啓動

所以下面添加一行代碼中的

final JFXPanel fxPanel = new JFXPanel(); 

導入以下包

import javafx.embed.swing.JFXPanel; 

現在你的代碼看起來像這樣

import java.io.File; 
import javafx.embed.swing.JFXPanel; 
import javafx.scene.media.Media; 
import javafx.scene.media.MediaPlayer; 

public class Test { 

public static void main(String args[]) { 

    final JFXPanel fxPanel = new JFXPanel(); 
    String bip = "D://bip.mp3"; //sound file path 
    Media hit = new Media(new File(bip).toURI().toString()); 
    MediaPlayer mediaPlayer = new MediaPlayer(hit); 
    mediaPlayer.play(); 

    } 
} 
+0

現在我得到了:主線程「異常」MediaException:MEDIA_UNAVAILABLE:D:\ Waves.mp3(系統找不到文件) – CRHS

+0

檢查媒體文件名和路徑,因爲當我嘗試通過將bip.mp3更改爲bip1.mp3 (沒有這樣的文件)我得到了同樣的錯誤,所以請檢查文件名與適當的情況下。 –

+0

多數民衆贊成在有線...我檢查了5次,但仍然是相同的結果...我甚至選擇相同的名稱爲我的文件,以確保:( – CRHS