I trying to add a mp3 in to my scala gui using scalafx, but i have trouble how to add in to the scene

this is what i have, but it doesn't work...

val gameStage = new PrimaryStage {

  title = "Game Graphics"
  scene = new Scene(windowWidth, windowHeight) {
    var audio = new Media(url)
    var mediaPlayer = new MediaPlayer(audio)
    mediaPlayer.volume = 100
    mediaPlayer.play()
  }
}

1 Answers

1
Mike Allen On Best Solutions

It appears that one problem is that you have not used a MediaView instance to add the MediaPlayer to the scene. Also, it's probably better if you do not start to play the media until the scene has been displayed.

I think you need something like this (as a complete app):

import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.scene.{Group, Scene}
import scalafx.scene.media.{Media, MediaPlayer, MediaView}

object GameGraphics
extends JFXApp {

  // Required info. Populate as necessary...
  val url = ???
  val windowWidth = ???
  val windowHeight = ???

  // Initialize the media and media player elements.
  val audio = new Media(url)
  val mediaPlayer = new MediaPlayer(audio)
  mediaPlayer.volume = 100

  // The primary stage is best defined as the stage member of the application.
  stage = new PrimaryStage {

    title = "Game Graphics"
    width = windowWidth
    height = windowHeight
    scene = new Scene {

      // Create a MediaView instance of the media player, and add it to the scene. (It needs
      // to be the child of a Group, or the child of a subclass of Group).
      val mediaView = new MediaView(mediaPlayer)
      root = new Group(mediaView)
    }

    // Now play the media.
    mediaPlayer.play()
  }
}

Also, you should prefer val to var, particularly if there is no need to modify the associated variables after they have been defined.

BTW, it's not possible to test your code, so please consider posting a minimal, complete and verifiable example next time.