在 java 中创建音频播放器
Creating audio player in java
我正在尝试使用 java 播放一个简单的 mp3 文件。我写的代码是:
public void playAudio(String fileSource) {
try (InputStream music = new FileInputStream(fileSource)) {
AudioStream audioStream = new AudioStream(music);
AudioPlayer.player.start(audioStream);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "error");
}
}
但是当我为方法提供文件路径时,没有播放任何内容。缺少什么代码?谢谢
您的示例可以播放 midi、wav 文件,也许还有一些其他文件,但不能播放 mp3,因为专利问题,但是如果您可以使用 JavaFX,那么您可以像这样播放 mp3:
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class MainClass {
public static void main(String[] args) {
com.sun.javafx.application.PlatformImpl.startup(()->{});
Media sound = new Media(new File("C:\Users\SomeUser\Desktop\someFile.mp3").toURI().toString());
MediaPlayer player = new MediaPlayer(sound);
player.play();
try {
Thread.sleep(20000); //don't exit too early
} catch (InterruptedException e) {
e.printStackTrace();
}
com.sun.javafx.application.PlatformImpl.exit();
}
}
否则你可以使用一些其他的库,比如Java Stream Player
顺便说一下,您的初始示例的正确语法是:
InputStream in = null;
try {
in = new FileInputStream("someFile.wav");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
AudioStream as = null;
try {
as = new AudioStream(in);
} catch (IOException e) {
e.printStackTrace();
}
AudioPlayer.player.start(as);
我正在尝试使用 java 播放一个简单的 mp3 文件。我写的代码是:
public void playAudio(String fileSource) {
try (InputStream music = new FileInputStream(fileSource)) {
AudioStream audioStream = new AudioStream(music);
AudioPlayer.player.start(audioStream);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "error");
}
}
但是当我为方法提供文件路径时,没有播放任何内容。缺少什么代码?谢谢
您的示例可以播放 midi、wav 文件,也许还有一些其他文件,但不能播放 mp3,因为专利问题,但是如果您可以使用 JavaFX,那么您可以像这样播放 mp3:
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class MainClass {
public static void main(String[] args) {
com.sun.javafx.application.PlatformImpl.startup(()->{});
Media sound = new Media(new File("C:\Users\SomeUser\Desktop\someFile.mp3").toURI().toString());
MediaPlayer player = new MediaPlayer(sound);
player.play();
try {
Thread.sleep(20000); //don't exit too early
} catch (InterruptedException e) {
e.printStackTrace();
}
com.sun.javafx.application.PlatformImpl.exit();
}
}
否则你可以使用一些其他的库,比如Java Stream Player
顺便说一下,您的初始示例的正确语法是:
InputStream in = null;
try {
in = new FileInputStream("someFile.wav");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
AudioStream as = null;
try {
as = new AudioStream(in);
} catch (IOException e) {
e.printStackTrace();
}
AudioPlayer.player.start(as);