如何让java放出音乐

一个Music类

music.java

package indi.wscmars.game;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Music
{
	private File file;//.wav
	private AudioInputStream stream;
	private AudioFormat format;
	private DataLine.Info info;
	private Clip clip;
	
	//open the music
	void open(String s)
	{
		file = new File(s);
		try 
		{
			stream = AudioSystem.getAudioInputStream(file);
			format = stream.getFormat();
		}
		catch (UnsupportedAudioFileException e) 
		{
			e.printStackTrace();
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	void play()
	{
		info = new DataLine.Info(Clip.class, format);
		try 
		{
			clip = (Clip) AudioSystem.getLine(info);
			clip.open(stream);
		} 
		catch (LineUnavailableException e) 
		{
			e.printStackTrace();
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	void start()
	{
		clip.start();
	}	
	
	void loop() 
	{
		clip.loop(1);;
	}
}

在main方法中播放音乐

package indi.wscmars.game;

public class Main 
{
	static Music music;
	
	public static void main(String[] args) 
	{
            //play music
            if(music == null)
            {
        	music = new Music(); 
        	music.open("Butter_Fly.wav");	
		music.play();
		music.loop();
            }
        }
}

 

你可能感兴趣的:(如何让java放出音乐)