Playing MP3 and WAV Audio Files in Java
In Java, playing audio files can be achieved through APIs such as Java Sound, which provides support for playback of WAV files. However, playing MP3 files requires additional dependencies, such as the JavaFX Media and MediaPlayer classes.
To play both MP3 and WAV files using the same method in Java Swing, the JavaFX platform can be utilized. JavaFX offers more comprehensive audio support, including playback of MP3 audio format.
Example Code
import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; public class AudioPlayer { public static void playSound(String filePath) { try { // Create a Media object for the specified file Media media = new Media(new File(filePath).toURI().toString()); // Create a MediaPlayer object and play the audio MediaPlayer mediaPlayer = new MediaPlayer(media); mediaPlayer.play(); } catch (Exception ex) { System.out.println("Error with playing sound."); ex.printStackTrace(); } } public static void main(String[] args) { // Example WAV file path String wavFile = "path/to/file.wav"; // Example MP3 file path String mp3File = "path/to/file.mp3"; // Play both files using the same method playSound(wavFile); playSound(mp3File); } }
Additional Notes
The above is the detailed content of How Can I Play Both MP3 and WAV Audio Files in Java Using a Single Method?. For more information, please follow other related articles on the PHP Chinese website!