我的歌曲表現有問題。我有一個從filechooser加載的音軌列表,放置在TableView中並存儲在列表(播放器)中。通過getSelectionModel採取選定的音頻文件,我運行它,迄今如此好。如果您不停下來並選擇另一個音頻文件併發送給您播放,則會疊加聲音。我怎樣才能停止執行前一個文件,從而避免多重播放?如何防止使用mediaplayer javafx進行多重播放?
addFileAudio代碼:
Media media;
final List<MediaPlayer> players = new ArrayList<>();
String fileName;
MediaPlayer mediaPlayer;
public void addFileAudio(ActionEvent event) {
BasicFileAttributes attr = null;
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Seleziona il file da caricare");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Audio Files","*.wav","*.mp3"));
File selectedFile = fileChooser.showOpenDialog(new Stage());
if (selectedFile != null) {
media = new Media(new File(selectedFile.getAbsolutePath()).toURI().toString());
mediaPlayer = new MediaPlayer(media);
players.add(mediaPlayer);
MediaView mediaView = new MediaView(mediaPlayer);
mediaView.setMediaPlayer(mediaPlayer);
Path pathFile = Paths.get(selectedFile.toURI());
try {
attr = Files.readAttributes(pathFile, BasicFileAttributes.class);
} catch (IOException e) {
Exception.showError(1);
}
}else{
Exception.showWarning(0);
}
String fileName = selectedFile.getName();
String data = attr.creationTime().toString().substring(0,10);
Table1.getItems().add(new PopulateTable(Table1.getItems().size()+1, fileName, data));
}
代碼播放按鈕:
void play(ActionEvent event) {
MediaPlayer player = players.get(Table1.getSelectionModel().getSelectedIndex()); Status status = player.getStatus();
if (status!= Status.PLAYING) {
player.play();
} else {
MediaPlayer playerNext = players.get(Table1.getSelectionModel().getSelectedIndex()); player.stop(); playerNext.play(); }
狀態狀態不應該在您的play()方法中。它應該是靜態的和全球的。然後一旦你按播放()你播放歌曲,然後設置狀態播放 – Sedrick