如何在scalafx gui场景中添加mp3?

时间:2019-04-05 02:22:13

标签: scalafx

我试图使用scalafx将mp3添加到我的scala gui中,但是我很难将其添加到场景中

这是我所拥有的,但不起作用...

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 个答案:

答案 0 :(得分:1)

似乎有一个问题是您没有使用MediaView实例将MediaPlayer添加到场景中。另外,最好在显示场景之前不开始播放媒体。

我认为您需要这样的东西(作为一个完整的应用程序):

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()
  }
}

此外,您应该更喜欢val而不是var,尤其是在定义了关联变量之后无需修改它们的情况下。

顺便说一句,无法测试您的代码,因此请考虑下次发布minimal, complete and verifiable example