forked from fjoneus/Musikspelare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MusicPlayer.java
96 lines (74 loc) · 1.94 KB
/
MusicPlayer.java
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* This music player can take in a file from an object. Extract the file name (source of the file), and find the file.
* The player hold all the necessary methods for play, pause and so on.
*
*
* @author fjoneus
*
*/
import java.util.*;
import java.io.*;
import javax.sound.sampled.*;
public class MusicPlayer {
private AudioInputStream songFile;
private Clip song;
private long currentPos;
private File file;
/**
* Constructor -> Extracts the songName from the Item object and creates the AudioInputStream
*/
public MusicPlayer(String x) {
try {
//File file = new File(x.getSongFile()); //Create the File object that holds the path to the file
file = new File(x);
songFile = AudioSystem.getAudioInputStream(file.getAbsoluteFile()); //Set the "private songFile" so it can be used later in the program. AudioSystem returns a AudioInputStream object
}
catch(Exception e) {
System.out.println(e);
}
}
/**
* Creates a Clip object true AudioSystem, uses the open and start method from Clip to play the songFile.
* If the song has been on pause the song will start playing from currentPosition
* @exception Catches all the exceptions and prints them
*/
public void play() {
try {
if(currentPos > 0) {
song.setMicrosecondPosition(currentPos);
song.start();
}
else {
song = AudioSystem.getClip();
song.open(songFile);
song.start();
}
}
catch(Exception e) {
System.out.println(e);
}
}
/**
* Saves the current position and stops the Clip.
*/
public void pause(){
currentPos = song.getMicrosecondPosition();
song.stop();
}
/**
* Stops the Clip.
*/
public void stop(){
song.stop();
}
public static void main(String[] args) {
MusicPlayer test = new MusicPlayer("Bamse.wav");
test.play();
Scanner scanner = new Scanner(System.in);
scanner.next();
test.pause();
scanner.next();
test.play();
scanner.close();
}
}