-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMusicPlayer.java
More file actions
82 lines (61 loc) · 2.22 KB
/
MusicPlayer.java
File metadata and controls
82 lines (61 loc) · 2.22 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
76
77
78
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class MusicPlayer {
Long currentFrame;
Clip clip;
// current status of clip
String status;
AudioInputStream audioInputStream;
static String filePath;
// constructor to initialize streams and clip
public MusicPlayer(String filePath) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
// create AudioInputStream object
audioInputStream = AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
// create clip reference
clip = AudioSystem.getClip();
// open audioInputStream to the clip
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
public void play() {
//start the clip
clip.start();
status = "play";
}
public void stop() {
currentFrame = 0L;
status = "stop";
clip.stop();
clip.close();
}
public void pause() {
this.currentFrame =
this.clip.getMicrosecondPosition();
clip.stop();
status = "paused";
}
public void resumeAudio() throws UnsupportedAudioFileException,
IOException, LineUnavailableException {
clip.close();
resetAudioStream();
clip.setMicrosecondPosition(currentFrame);
this.play();
}
public void resetAudioStream() throws UnsupportedAudioFileException, IOException,
LineUnavailableException {
audioInputStream = AudioSystem.getAudioInputStream(
new File(filePath).getAbsoluteFile());
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
public float getVolume() {
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
return (float) Math.pow(10f, gainControl.getValue() / 20f);
}
public void setVolume(float volume) {
if (volume < 0f || volume > 1f) throw new IllegalArgumentException("Volume not valid: " + volume);
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(20f * (float) Math.log10(volume));
}
}