'"player" cannot be resolved or is not a field, How to solve this compilation error?
I'm trying to play music in Java but I'm unable to solve this.
package Mplayer;
import java.io.File;...
public class Music
{
private static final String AudioPlayer = null;
public static void main(String[] args)...
public static void playMusic(String filepath)
{
InputStream music;
try
{
music = new FileInputStream(new File(filepath));
AudioInputStream audios = new AudioInputStream((TargetDataLine) music);
AudioPlayer.player.start(audios);
}
catch (Exception e)
{
// TODO: handle exception
JOptionPane.showMessageDialog(null, "Error");
}
}
}
The player wouldn't work no matter what I change it into.
Solution 1:[1]
It does not compile because, the type of AudioPlayer is String.
A more detailed explanation:
You are using reserve classes. See https://stackoverflow.com/a/7676877/18274209
Also see this working version (Tested in Java 11.0.2):
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class Music {
public static void main(String[] args) {
playMusic("<YOUR_FILEPATH_GOES_HERE>");
}
public static void playMusic(String filepath) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(
new File(filepath)
);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
Thread.sleep(10000);
} catch (Exception ex) {
System.out.println(ex);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel Victoriano Bremont |
