"player" cannot be resolved or is not a field, How to solve this compilation error?

381 Views Asked by At

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.

1

There are 1 best solutions below

2
On

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);
    }
  }
}

See https://stackoverflow.com/a/12059638/18274209.