java
1 public void setFile(String soundFileName) {
2 try {
3 if(clip != null) {
4 clip.close();
5 }
6
7 //
8 File file = new File(soundFileName);
9 AudioInputStream sound = AudioSystem.getAudioInputStream(file);
10 clip = AudioSystem.getClip();
11 clip.open(sound);
12 sound.close();
13 }
14 catch(Exception e) {
15 }
16 }
clipとsoundをきちんとcloseしてあげればいいようです。
Kotlin + JavaFXのサンプルですが、java -Xmx16m ...
で、問題なく実行できます。closeを端折ると、速攻でOutOfMemoryError。
Kotlin
1import javafx.application.Application
2import javafx.application.Platform
3import javafx.scene.Scene
4import javafx.scene.control.Button
5import javafx.scene.control.TextArea
6import javafx.scene.layout.VBox
7import javafx.stage.Stage
8import java.io.File
9import java.nio.file.Paths
10import java.time.LocalTime
11import javax.sound.sampled.AudioSystem
12import javax.sound.sampled.Clip
13import kotlin.concurrent.thread
14
15object xxSound {
16
17 @JvmStatic
18 fun main(args: Array<String>) {
19 Application.launch(App::class.java, *args)
20 }
21
22 class App : Application() {
23 override fun start(stage: Stage) {
24 var clip: Clip? = null
25
26 fun setFile(file: File) {
27 AudioSystem.getAudioInputStream(file).use { sound ->
28 clip?.close()
29
30 clip = AudioSystem.getClip()
31 clip?.open(sound)
32 }
33 }
34
35 val play = Button("Play").also { button ->
36 button.setOnAction { ev ->
37 val file = Paths.get("/tmp/ss.wav").toFile()
38 setFile(file)
39 clip?.start()
40 }
41 }
42 val stop = Button("Stop").also { button ->
43 button.setOnAction { ev ->
44 clip?.stop()
45 }
46 }
47
48 val text = TextArea()
49 thread {
50 while (true) {
51 Platform.runLater {
52 val free = Runtime.getRuntime().freeMemory()
53 val total = Runtime.getRuntime().totalMemory()
54 val used = free * 100.0 / total
55 val msg = "${LocalTime.now()} // ${used} = ${free} / ${total}"
56 text.text = "${msg}\n${text.text}"
57 }
58 Thread.sleep(1000)
59 }
60 }
61
62 val box = VBox(play, stop, text)
63 stage.scene = Scene(box)
64 stage.title = xxSound::javaClass.name
65 stage.show()
66 }
67 }
68}