Search code examples
javaaudiojavasoundstack-overflow

How do I make this sound loop?


I am trying to loop the sound in this code. In the finally block of the main try and catch I do this :

    if (loop) {
        auline.flush();
        run();
    } else {
        ended=true;
        auline.drain();
        auline.close();
    }

but it causes a stackoverflow. How can I safely loop this sound without creating a new instance of it?


Solution

  • You're calling run from within run, this will eventually fill up the call stack & result in your stack overflow exception

    Now, the question is, how do you overcome it?

    You need to loop within the run method. The best way I can think of is to have a "exit" trigger in the run method

    public void run() {
        while(loop) {
            //...play sound
        }
    }
    

    You could the use stop method to also trigger the loop flag