-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMediaPlayer.java
More file actions
75 lines (62 loc) · 2.39 KB
/
MediaPlayer.java
File metadata and controls
75 lines (62 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class MediaPlayer implements LineListener {
// Private class variable to check if media has finished playing
private static boolean mediaFinished;
// Play media from the specified file
public static void play(File mediaFile)
{
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(mediaFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip)AudioSystem.getLine(info);
audioClip.open(audioStream);
audioClip.start();
// Delay until media has finished playing
while(!(mediaFinished))
{
if(!(FileHandler.currentMode.equals("Zen Mode")))
{
break;
}
Thread.sleep(1000);
// Delay an extra 5 seconds when switching songs
if(mediaFinished)
{
Thread.sleep(5000);
}
}
audioClip.close();
}
catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
} catch (LineUnavailableException e2) {
e2.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
} catch (InterruptedException e4) {
e4.printStackTrace();
}
}
// Overrided LineEventListener.update() method to check playing time of media
@Override
public void update(LineEvent event) {
LineEvent.Type type = event.getType();
if (type == LineEvent.Type.START) {
System.out.println("Playback started.");
} else if (type == LineEvent.Type.STOP) {
mediaFinished = true;
System.out.println("Playback completed.");
}
}
}