enneenne
enneenne

Reputation: 219

Java Mediaplayer - play again

Here is my code:

public abstract class Car {

    MediaPlayer mediaPlayer;

    public Car() {

    }

    public void sound() {
        mediaPlayer.play();
    }

}

public class BlueCar extends Car{
    
    public BlueCar() {
        String path = "src/sound_horn_1.mp3";
        Media hit = new Media(new File(path).toURI().toString());
        mediaPlayer = new MediaPlayer(hit);
    }
    
    public void addCarOnRoad() {
        //
    }
}

public class Road {
    
    List<Car> cars = new ArrayList<>();
    
    public void chooseAnyAndMakeHorn() {
        Random rnd = new Random();
        cars.get(rnd.nextInt((cars.size() - 0) + 1) + 0);
    }
}

So every object Car has its own sound (mediaplayer instance) and I want to play that sound more than once from any Car instance.

But it works only once for each car - once the sound is played, it cannot be played again from the same car.

Where am I going wrong?

Is there some special method I should call after mediaPlayer.play() to make it possible to play again?

Upvotes: 0

Views: 383

Answers (1)

Kitswas
Kitswas

Reputation: 1195

What happened:

Reaching the end of the media (or the stopTime if this is defined) while playing does not cause the status to change from PLAYING. Therefore, for example, if the media is played to its end and then a manual seek to an earlier time within the media is performed, playing will continue from the new media time.

https://docs.oracle.com/javafx/2/api/javafx/scene/media/MediaPlayer.Status.html

https://docs.oracle.com/javafx/2/api/javafx/scene/media/MediaPlayer.html#startTimeProperty()

What could be done:

Solution 1

Try putting mediaPlayer.setStartTime(Duration.Zero); before mediaPlayer.play();.

Solution 2

Try putting mediaPlayer.seek(Duration.Zero); before mediaPlayer.play();.

Upvotes: 1

Related Questions