我已经看过并尝试了AudioCLip,MediaPlayer等多种功能,但没有任何效果。另外,我也不知道URL或URI系统如何工作。在那里,我再次看到了很多东西,但不知道哪个是正确的。
这是我上次尝试使用的代码:
public void start (Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
//Initialising path of the media file, replace this with your file path
//File is in the same project with the following path:
String path = "file:src/SoundTest/Megalovania.mp3";
File file = new File(path);
//Instantiating Media class
if(file.exists()) {
Media media = new Media(file.getPath());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
} else{
System.out.println("file not found");
}
//Instantiating MediaPlayer class
//by setting this property to true, the audio will be played
primaryStage.setTitle("Playing Audio");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
如果URL正确,有人可以告诉我是否可行?如果没有,还有什么不对?
答案 0 :(得分:0)
此代码有效,但仅当您有其他场景(如场景)时,否则代码会提早停止。不确定是否可以使用空台。
import javafx.application.Application;
import javafx.scene.image.Image;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.File;
import java.net.URISyntaxException;
public class AudioTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
String musicFile = "Megalovania.mp3"; // For example
Media sound = null;
try {
sound = new Media(getClass().getResource(musicFile).toURI().toString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
MediaPlayer mediaPlayer = new MediaPlayer(sound);
mediaPlayer.play();
}
}
一直是路径/资源。我现在已经感谢我的老师了。