Java Jlayer Mp3 Player - how to repeat and stop song [closed]

时光毁灭记忆、已成空白 提交于 2019-12-01 13:00:41

JLayer does not support continuous play, so you have to use a loop to repeatedly start a new player after the old one finished. For example:

try { do { FileInputStream buff = new FileInputStream(Okno.filename); prehravac = new AdvancedPlayer(buff ); prehravac .play(); }while(loop); } catch(Exception ioe) { //TODO error handling }

with loop being a boolean you can set true or false in a different method depending on if you want it to be played just once or repeatedly.

If you want to access the thread later you should at least declare it to a variable. Even better is writing a seperate class that extends thread. Doing so you can add method to the thread you can later call.

For your code it might look something like that:

import java.io.*;
import javazoom.jl.player.*;

public class MyAudioPlayer extends Thread {

    private String fileLocation;
    private boolean loop;
    private Player prehravac;

    public MyAudioPlayer(String fileLocation, boolean loop) {
        this.fileLocation = fileLocation;
        this.loop = loop;
    }

    public void run() {

        try {
            do {
                FileInputStream buff = new FileInputStream(fileLocation);
                prehravac = new Player(buff);
                prehravac.play();
            } while (loop);
        } catch (Exception ioe) {
            // TODO error handling
        }
    }

    public void close(){
        loop = false;
        prehravac.close();
        this.interrupt();
    }
}

With this you can simply create the Thread when and wherever you want like this:

private MyAudioPlayer thePlayer;

    [... some class code here...]

    public void yourMethod(){
        thePlayer = new MyAudioPlayer("path of the music file", true);
        thePlayer.start();
    }

and if you want to get rid of it at some point call thePlayer.close(); Note that thePlayer should be an instance variable so you can reuse it again. If you only declare it within a method it will disappear after the method is finished.

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!