2017-10-20 66 views
0

我正在尝试使用JavaFX开发音频播放器。所以,到现在为止,我的音频播放器具有这些基本功能 - 打开,播放,暂停,停止,音量滑块和搜索栏。 这是问题,当我运行应用程序并打开任何歌曲时,它开始播放。但当我打开其他任何使用(使用FileChooser和在后台,前一首歌曲仍在播放)时,它也开始与前一首歌曲一起播放(它一直在播放)。那么,我该如何 - 当我弹奏新歌时,前一首停止。这里是我的FXMLController代码:如何在JavaFX中停止以前的歌曲

public void open(ActionEvent e){ 


    FileChooser fc = new FileChooser(); 
    selectedFile = fc.showOpenDialog(null); 

    if(selectedFile != null){ 

    String path = selectedFile.getAbsolutePath(); 

    path = path.replace("\\","/"); 
    me = new Media(new File(path).toURI().toString()); 
    mp = new MediaPlayer(me); 
    mv.setMediaPlayer(mp); 
    musicBox.setText(path); 
    volumeSlider.setValue(0.7 * 100); 
    volumeSlider.valueProperty().addListener((Observable observable) -> { 
    mp.setVolume(volumeSlider.getValue()/100); 
    }); 

    mp.currentTimeProperty().addListener((ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) -> { 
     seekSlider.setValue(newValue.toSeconds()); 
    }); 

    seekSlider.setOnMouseClicked((MouseEvent event) -> { 
     mp.seek(Duration.seconds(seekSlider.getValue())); 
    }); 

    mp.play(); 

    } 
} 
public void play(ActionEvent e){ 
mp.play(); 
} 

public void pause(ActionEvent e){ 
mp.pause(); 
} 

public void stop(ActionEvent e){ 
mp.stop(); 
} 


@Override 
public void initialize(URL url, ResourceBundle rb) { 


} 

回答

0

只要停止以前的声音,像

if(selectedFile != null){ 
    String path = selectedFile.getAbsolutePath(); 
    if(mp!=null) mp.stop(); 
    //rest of code 
+1

可能需要在'mp'空校验,第一个选择的情况。 –

+1

@James_D谢谢。我现在已经考虑到了这一点。 –

+0

非常感谢! @FrankUnderwood:D它工作! 会问关于这个项目的更多问题:P –

相关问题