⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 music.java

📁 wiziqi
💻 JAVA
字号:
package vo.sounds;

import javax.sound.midi.*;
import java.io.*;
import java.net.*;

/**
 * 控制背景音乐
 */
public class Music implements MetaEventListener, Runnable {
  private String midiFile = "mis/CLASSIC.MID";

  private Sequence sequence;

  private Sequencer sequencer;

  private boolean isPlaying = false;

  private volatile Thread thread;

  public Music() {
    try {
      loadMidi(midiFile);
    } catch (InvalidMidiDataException ex) {
    } catch (IOException ex) {
    } catch (NullPointerException ex) {
      System.out.println(ex.getMessage() + "\n背景音乐文件未找到!");
      if(sequence == null) {
        System.out.println("null呀null");
        System.exit(0);
      }
    }
  }

  /**
   * 读取midi文件
   */
  public void loadMidi(String fileName) throws IOException,
      InvalidMidiDataException {
    URI uri = new File(fileName).toURI();
    URL url = uri.toURL();
    System.out.println(url);/////////////////////%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    sequence = MidiSystem.getSequence(url);
  }

  public void play() {
    if (isPlaying) { // 如果已经在播放,返回
      return;
    }

    try {
      sequencer = MidiSystem.getSequencer();
      sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
      sequencer.open();
      sequencer.setSequence(sequence);

      sequencer.addMetaEventListener(this);
    } catch (InvalidMidiDataException ex) {
    } catch (MidiUnavailableException ex) {
    }

    thread = new Thread(this);
    thread.start();
  }

  public void stop() {
    System.out.println(isPlaying);
    if (isPlaying) {
      sequencer.stop();
      isPlaying = false;
    }
    if (thread != null) {
      thread = null;
    }
  }

  @SuppressWarnings("static-access")
  public void run() {
    Thread currentThread = Thread.currentThread();
    while (currentThread == thread && !isPlaying) {
      try {
        sequencer.start();
        isPlaying = true;
        thread.sleep(1000l);
      } catch (InterruptedException ex) {
      } catch (IllegalStateException ex) {
        System.out.println(ex.getMessage());
      }
    }
  }

  public void meta(MetaMessage event) {
    if (event.getType() == 47) {
      System.out.println("Sequencer is done playing.");
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -