-1

我正在尝试用 Java 播放音乐,但我无法解决这个问题。

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

不管我把它改成什么,播放器都不会工作。

4

1 回答 1

0

它无法编译,因为AudioPlayer的类型是 String。

更详细的解释:

您正在使用保留课程。见https://stackoverflow.com/a/7676877/18274209

另请参阅此工作版本(在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);
    }
  }
}

请参阅https://stackoverflow.com/a/12059638/18274209

于 2022-02-24T12:21:51.073 回答