JAVA播放背景音乐

播放音乐方法大致分为两类:

1、只能播放.wav格式的,Java自带的。

package com.snow;

import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.URI;
import java.net.URL;

public class Music extends Thread{
	private File f;
	private URI uri;
	private URL url;


	public void run() { // 注意,java只能播放无损音质,如.wav这种格式
		try {
			
			f = new File("飞雪玉花.wav"); // 绝对路径
			uri = f.toURI();
			url = uri.toURL(); // 解析路径
			AudioClip aau;
			aau = Applet.newAudioClip(url);
			aau.loop(); // 单曲循环
			System.out.println("");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

2、可以播放.mp3格式,需要导入第三方的包。

http://www.javazoom.net/javalayer/javalayer.html

package com.snow;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.*;


public class MusicMp3 extends Thread {
	Player player;
	File music;

	public MusicMp3() {
		this.music = new File("飞雪玉花.mp3");;
	}

	@Override
	public void run() {
		super.run();
		try {
			play();
		} catch (FileNotFoundException | JavaLayerException e) {
			e.printStackTrace();
		}
	}

	public void play() throws FileNotFoundException, JavaLayerException {
		BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(music));
		player = new Player(buffer);
		player.play();
	}
}

 

你可能感兴趣的:(JAVA)