如何在jlayer中停止MP3?(不再使用the stop()
)
我的代码如下:
//main class mp3_main
private AdvancedPlayer player;
public static void main(String[] args) {
String file="C:\cd.mp3";
mp3PlayerSample mp3 = new mp3PlayerSample(file);
mp3.play();
mp3.stop();
}
//class mp3PlayerSample
private String filename;
private BufferedInputStream buffer;
private AdvancedPlayer player;
//constructor
public mp3PlayerSample(String filename)
{
this.filename = filename;
}
//start method
public void play()
{
FileInputStream fis;
try {
fis = new FileInputStream(this.filename);
buffer = new BufferedInputStream(fis);
try {
this.player=new AdvancedPlayer(buffer);
player.play();
} catch (JavaLayerException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//stop method
public void stop()
{
if(player != null){
player.close();
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import java.util.Scanner;
class Music extends Thread{
public void run(){
try {
FileInputStream fileInputStream = new FileInputStream("Freedom.mp3");
Player player = new Player(fileInputStream);
player.play();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(JavaLayerException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main (String[]args){
Scanner keyboard = new Scanner(System.in);
Music music = new Music();
music.start();
System.out.println("Stop music: ");
int off = keyboard.nextInt();
if(off == 0) {
music.stop();
}
}
}
您需要在播放器自己的线程中运行播放器,现在您的主方法在调用play()之后阻塞,直到播放完成。
注意,jlayer中包含的类Player/AdvancedPlayer是示例代码,用于演示解码音频的解码和输出必须如何连接。他们不是成熟的玩家(例如,甚至没有音量控制)。