Hello guys I have tried or still trying to play that Java-audio code and it does not work even when the code is right. Note: The audiofile is in the same folder as the code-file and I have converted the audio file into a .wav file, so from .mp3 to .wav. Could someone provide me with a good explained solution so that a five year old could understand it:)
My code:
package audio;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.*;
public class Main {
public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
Scanner scanner0 = new Scanner(System.in); // Create a Scanner object for user input
File audio = new File("IFKC.wav"); // Create a File object for the .wav file
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audio); // Get an audio stream from the .wav file
Clip clip = AudioSystem.getClip(); // Create a Clip object for playing the audio
clip.open(audioStream); // Open the audio stream in the Clip
String response = ""; // Initialize the response string
while (!response.equals("Q")) { // Keep looping until the user enters "Q"
System.out.println("P = play, S = Stop, R = reset, Q = quit"); // Prompt the user for a choice
System.out.print("Enter your choice: ");
response = scanner0.next(); // Read the user's input
response = response.toUpperCase(); // Convert the input to uppercase
switch (response) { // Act based on the user's choice
case "P":
clip.start(); // Start playing the audio
break;
case "S":
clip.stop(); // Stop playing the audio
break;
case "R":
clip.setMicrosecondPosition(0); // Reset the audio to the beginning
break;
case "Q":
clip.close(); // Close the audio stream
break;
default:
System.out.println("Not a valid response"); // Handle invalid input
}
}
System.out.println("You have left the audio!"); // Says goodbye when the user enters "Q"
}
}
output:
Exception in thread "main" java.io.FileNotFoundException: IFKC.wav (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.desktop/com.sun.media.sound.SunFileReader.getAudioInputStream(SunFileReader.java:117)
at java.desktop/javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1062)
at audio.Main.main(Main.java:15)
>Solution :
You can try the following fixes.
1: In audio = new File("IFKC.wav") try passing the complete path to the file like C:\projects\directory\filename
2: Your file should directly be under the project folder, and not inside any other sub-folder. So make sure your file IFKC.wav is directly in the project folder where your .class files are present. Then try again.
Hope that helps.