· 6 years ago · Dec 21, 2019, 04:10 AM
1
2package GUISamples
3
4
5import javafx.application.Application
6import javafx.application.Platform
7import javafx.beans.InvalidationListener
8import javafx.collections.FXCollections
9import javafx.collections.MapChangeListener
10import javafx.scene.Scene
11import javafx.scene.control.*
12import javafx.scene.control.cell.PropertyValueFactory
13import javafx.scene.layout.BorderPane
14import javafx.scene.layout.HBox
15import javafx.scene.layout.VBox
16import javafx.scene.media.Media
17import javafx.scene.media.MediaPlayer
18import javafx.stage.FileChooser
19import javafx.stage.FileChooser.ExtensionFilter
20import javafx.stage.Stage
21import java.io.File
22import java.sql.*
23import java.time.format.DateTimeFormatter
24import kotlin.math.floor
25
26
27class sql {
28
29 fun create(fileName: String) {
30 val url = "jdbc:sqlite:D:/java2/$fileName"
31 val sql2 = ("CREATE TABLE IF NOT EXISTS music_library (\n"
32 + " id integer PRIMARY KEY,\n"
33 + " name text NOT NULL,\n"
34 + " artist text\n"
35 + " album text\n"
36 + " genre text\n"
37 + " year integer\n"
38 + " duration text\n"
39 + " dir text\n"
40
41 + ");")
42 try {
43 val conn = DriverManager.getConnection(url)
44 val stmt: Statement = conn.createStatement()
45 stmt.execute(sql2)
46 } catch (e: SQLException) {
47 println(e.message)
48 }
49
50 }
51
52 private fun connect(fileName: String): Connection? {
53 val url = "jdbc:sqlite:D:/java2/$fileName"
54 var conn: Connection? = null
55 try {
56 conn = DriverManager.getConnection(url)
57 } catch (e: SQLException) {
58 println(e.message)
59 }
60 return conn
61 }
62
63 fun insert(name: String?, artist: String?, album: String?, genre: String?, year: Int, duration: String?, dir: String?) {
64 val sql = "INSERT INTO music_library(name, artist, album, genre, year, duration, dir) VALUES(?,?)"
65 try {
66 val conn: Connection? = this.connect("db.db")
67 val pstmt: PreparedStatement? = conn?.prepareStatement(sql)
68 pstmt?.setString(1, name)
69 pstmt?.setString(2, artist)
70 pstmt?.setString(3, album)
71 pstmt?.setString(4, genre)
72 pstmt?.setInt(5, year)
73 pstmt?.setString(5, duration)
74 pstmt?.setString(6, dir)
75 pstmt?.executeUpdate()
76 } catch (e: SQLException) {
77 println(e.message)
78 }
79 }
80
81
82
83
84
85
86 fun drop() {
87 val sql = "DROP TABLE employees"
88 val conn: Connection? = this.connect("db.db")
89 val pstmt: PreparedStatement? = conn?.prepareStatement(sql)
90 pstmt?.executeUpdate()
91 }
92
93 fun print() {
94 val conn: Connection? = this.connect("db.db")
95 val stmt: Statement? = conn?.createStatement()
96 val rs = stmt?.executeQuery("SELECT * FROM employees")
97 while (rs!!.next()) {
98 val name = rs.getString("name")
99 print("$name ")
100 val cap = rs.getString("capacity")
101 println(cap + "\n")
102 }
103
104 }
105}
106
107
108class SongModel {
109
110 var artist : String? = "UNKNOWN"
111 var duration : String? = "UNKNOWN"
112 var title : String? = "UNKNOWN"
113 fun SetArtist(a : String){
114 this.artist = a
115 }
116 fun SetTitle(t : String){
117 this.title = t
118 }
119}
120
121class MPlayer : Application() {
122
123
124 var musicList = mutableListOf<Media>()
125 var index = 0
126 var curMusic = -1
127 var selectedMusic = -1
128 internal var selectedFile: File? = null
129 internal var mplayer: MediaPlayer? = null
130 private var songData = FXCollections.observableArrayList<SongModel>()
131 private var table = object : TableView<SongModel>(songData) {
132 init {
133 val column1 = TableColumn<SongModel, String>("title")
134 val column2 = TableColumn<SongModel, String>("artist")
135 val column3 = TableColumn<SongModel, String>("duration")
136 column1.cellValueFactory = PropertyValueFactory<SongModel, String>("title")
137 column2.cellValueFactory = PropertyValueFactory<SongModel, String>("artist")
138 column3.cellValueFactory = PropertyValueFactory<SongModel, String>("duration")
139 columns.addAll(column1, column2, column3)
140 }
141 }
142
143 private fun handleMetadata(key: String, value: Any, track: SongModel) {
144 val artist: String
145 val title: String
146 if (key == "artist") {
147 artist = value.toString()
148 track.SetArtist(artist)
149 }
150 if (key == "title") {
151 title = value.toString()
152 track.SetTitle(title)
153 }
154 }
155
156 private fun setFocusOnTrack(index: Int) {
157 table.requestFocus();
158 table.selectionModel.select(index);
159 table.focusModel.focus(index);
160 }
161
162 private fun playMusic(index: Int) {
163 if (index >= 0) {
164 mplayer?.stop()
165 media = musicList[index]
166 mplayer = MediaPlayer(media)
167 mplayer?.play()
168 songData[index].title;
169 curMusicLabel.text = songData[index].title + " - " + songData[index].artist;
170 //table.style = "-fx-background-color:lightcoral"
171 }
172
173 }
174
175 private fun setCurTime(s: String) {
176 curTrackTime.text = s
177 }
178
179
180 var media: Media? = null
181 internal var musicSlider: Slider = Slider()
182 val volumeSlider: Slider = Slider()
183 var curMusicLabel: Label = Label("UNKNOWN")
184 var curTrackTime: Label = Label("00 : 00")
185 @Throws(Exception::class)
186 override fun start(primaryStage: Stage) {
187 val root = object : BorderPane() {
188 init {
189 val filenameLabel = Label("")
190 val fileChooser = FileChooser()
191 fileChooser.title = "Open File"
192 fileChooser.extensionFilters.addAll(
193 ExtensionFilter("Audio Files", "*.wav", "*.mp3")
194 )
195 val vbox = object : VBox() {
196 init {
197 children.add(filenameLabel)
198 val hbox = object : HBox() {
199 init {
200 val playButton = Button("Play")
201 val pauseButton = Button("Pause")
202 val nextButton = Button("next")
203 val prevButton = Button("prev")
204
205 playButton.setOnAction { e ->
206 playMusic(table.selectionModel.focusedIndex)
207 curMusic = table.selectionModel.focusedIndex
208 }
209 pauseButton.setOnAction { e -> mplayer?.pause() }
210 nextButton.setOnAction { e ->
211 var media: Media? = null
212 if (curMusic > -1) {
213 curMusic = (curMusic + 1) % musicList.count()
214 setFocusOnTrack(curMusic)
215 playMusic(curMusic)
216 }
217 }
218 prevButton.setOnAction { e ->
219 if (curMusic > -1) {
220 curMusic = (curMusic + musicList.count() - 1) % musicList.count()
221 setFocusOnTrack(curMusic)
222 playMusic(curMusic)
223 }
224
225 }
226 val stopButton = object : Button("Stop") {
227 init {
228 setOnAction { e -> mplayer?.stop() }
229 }
230 }
231
232 volumeSlider.prefWidth = 100.0
233 volumeSlider.minWidth = 100.0
234 volumeSlider.value = 100.0
235 children.addAll(playButton, pauseButton, stopButton, nextButton, prevButton, volumeSlider)
236 }
237 }
238 children.addAll(hbox, curMusicLabel, musicSlider, curTrackTime)
239 }
240 }
241
242
243 center = vbox
244
245 val menubar = object : MenuBar() {
246 init {
247 val menu = object : Menu("File") {
248 init {
249 val selectMenuItem = object : MenuItem("Select") {
250 init {
251 setOnAction { e ->
252 val selectedFiles = fileChooser.showOpenMultipleDialog(primaryStage)
253
254 for (file in selectedFiles) {
255 if (file != null) {
256 mplayer?.stop();
257 val url = file.toURI()
258
259 println(url.toString())
260 var media = Media(url.toString())
261
262 mplayer = MediaPlayer(media)
263 val track = SongModel()
264 mplayer?.setOnReady { ->
265 print("GG")
266 val duration = media.duration
267 val minutes = floor(duration.toMinutes())
268 val seconds = floor(duration.toSeconds() % 60.0)
269
270 track.duration = minutes.toLong().toString() + ':' + seconds.toLong().toString()
271 val b = songData.add(track)
272 musicList.add(musicList.count(), media)
273 curMusic = musicList.count() - 1
274 setFocusOnTrack(curMusic)
275 musicSlider.min = 0.0
276 musicSlider.max = 100.0
277 }
278 table.setOnMousePressed { mouseEvent ->
279 table.isFocusTraversable = false;
280 if (mouseEvent.clickCount == 2) {
281 playMusic(table.selectionModel.focusedIndex)
282 curMusic = table.selectionModel.focusedIndex
283 setFocusOnTrack(curMusic)
284 }
285 }
286 media.metadata?.addListener(MapChangeListener { ch ->
287 if (ch.wasAdded()) {
288 print("read metadata")
289 val key = ch.key
290 val value = ch.valueAdded
291 handleMetadata(key, value, track)
292 }
293 })
294 }
295 }
296 }
297 }
298 }
299 val pauseMenuItem = MenuItem("Pause")
300 val playMenuItem = MenuItem("Play")
301 val stopMenuItem = MenuItem("Stop")
302
303 items.addAll(selectMenuItem, playMenuItem, pauseMenuItem, stopMenuItem)
304 }
305 }
306 menus.add(menu)
307 }
308 }
309 top = menubar
310 table.prefHeight = 1000.0
311 bottom = table
312 }
313 }
314 musicSlider.valueProperty().addListener(InvalidationListener {
315 if (musicSlider.isPressed) {
316 var newTime = musicSlider.value;
317 val duration = mplayer?.media?.duration;
318 mplayer?.seek(duration?.multiply(musicSlider.value / 100.0));
319 }
320 })
321 volumeSlider.valueProperty().addListener(InvalidationListener {
322 if (volumeSlider.isPressed()) {
323 mplayer?.setVolume(volumeSlider.value / 100) // It would set the volume
324 }
325 })
326 Thread(Runnable {
327 while (true) {
328 if (mplayer != null) {
329 val currentTime = mplayer?.currentTime!!.toSeconds()
330 val allTime = mplayer?.stopTime!!.toSeconds()
331 musicSlider.value = currentTime * 100.0 / allTime
332 println("Cur time " + currentTime * 100.0 / allTime)
333 Platform.runLater { ->
334 val minutes: Double = floor(mplayer?.currentTime!!.toMinutes())
335 val seconds: Double = floor(mplayer?.currentTime!!.toSeconds() % 60.0)
336 val time: String = '0' + (minutes.toInt()).toString() + (seconds.toInt()).toString()
337 val formatter = DateTimeFormatter.ofPattern("mm ss")
338 val text = String.format("%02d : %02d", minutes.toInt(), seconds.toInt())//time.format(formatter)
339 setCurTime(text)
340
341 }
342 }
343 try {
344 Thread.sleep(500)
345 } catch (e: InterruptedException) {
346 e.printStackTrace()
347 }
348 }
349 }).start()
350
351
352 val scene = Scene(root, 400.0, 500.0)
353
354 primaryStage.scene = scene
355 primaryStage.show()
356 }
357
358 companion object {
359 @JvmStatic
360 fun main(args: Array<String>) {
361 sql().create("db.db")
362 launch(MPlayer::class.java)
363 }
364 }
365
366}