jaro2gw
jaro2gw

Reputation: 133

How to play same audio clip multiple times using JavaFX MediaPlayer

I want to implement a simple task: when a button is clicked, I want to play a sound. I have 3 separate buttons that, when clicked, call the same function. In this function, I play the audio clip. The tricky part is: sometimes the buttons work just fine, sometimes not at all, which is super weird to me since they all call the same function.

I've browsed other javafx-audio-related questions but they are all about the audio not playing at all, whereas in my case it seems to play only sometimes?

FXML snippet:

<ImageView fx:id="bomb1" fitHeight="32.0" fitWidth="32.0" 
           onMouseClicked="#useTheBomb"
           pickOnBounds="true" preserveRatio="true">
    <Image url="@bombs/bomb1.png"/>
    <cursor>
        <Cursor fx:constant="HAND"/>
    </cursor>
</ImageView>
<ImageView fx:id="bomb2" fitHeight="32.0" fitWidth="32.0" 
           onMouseClicked="#useTheBomb"
           pickOnBounds="true" preserveRatio="true">
    <Image url="@bombs/bomb2.png"/>
    <cursor>
        <Cursor fx:constant="HAND"/>
    </cursor>
</ImageView>
<ImageView fx:id="bomb4" fitHeight="32.0" fitWidth="32.0" 
           onMouseClicked="#useTheBomb"
           pickOnBounds="true" preserveRatio="true">
    <Image url="@bombs/bomb4.png"/>
    <cursor>
        <Cursor fx:constant="HAND"/>
    </cursor>
</ImageView>

This code is placed in my FXML Controller class

private val explosion = App::class.java.getResource("/bombs/explosion.mp3").toString()
private fun explode() = MediaPlayer(Media(explosion)).play()

the function that is called by the buttons:

fun useTheBomb() {
        explode()

        /* rest of the function does not concern audio at all, 
         * but I include it in case there's maybe some voodoo magic 
         * underneath that I don't know about
         * bombArray: Array<ImageView>
         */        
        with(bombArray[brikks.bombs++]) {
            image = exploded
            onMouseClicked = null
            cursor = Cursor.DEFAULT
        }
}

I get no errors when clicking the buttons

I also modyfied my program to allow the buttons to be clicked multiple times, and out of 30 tries the audio failed to play 6 times randomly. I couldn't see a pattern.

Upvotes: 0

Views: 564

Answers (1)

jaro2gw
jaro2gw

Reputation: 133

Well, I found a workaround

private val explosion = Media(App::class.java.getResource("/bombs/explosion.mp3").toString())

and then inside the useTheBomb() function:

MediaPlayer(explosion).play()

Tried it like a 100 times and worked everytime. Don't know why tho.

Upvotes: 2

Related Questions