forked from google/thread-weaver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayer.java
More file actions
67 lines (55 loc) · 1.88 KB
/
Player.java
File metadata and controls
67 lines (55 loc) · 1.88 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
/*
* Copyright 2009 Weaver authors
*
* This code is part of the Weaver tutorial and may be freely used.
*/
import java.util.HashMap;
import java.util.Map;
/**
* Provides a layer between a {@link Controller} that plays audio, and the
* underlying {@link AudioService}. Maintains a mapping between the
* audio tokens used by the AudioService and the corresponding controller
* object.
* <p>
* This is a simplified version of a real class, and is used to
* illustrate potential race conditions.
*
* @author alasdair.mackintosh@gmail.com (Alasdair Mackintosh)
*/
public class Player implements AudioListener {
/** Maps an audio token onto the corresponding Controller */
private Map<Integer, Controller> controllerMap = new HashMap<Integer,Controller>();
private AudioService service;
public Player(AudioService service) {
this.service = service;
}
/**
* Plays the given media asset. When the asset has finished playing,
* invokes {@link Controller#onFinished}.
*/
public int playAsset(String assetName, Controller controller) {
validateAsset(assetName);
// Start playing the asset, and get the token that identifies the audio stream.
int token = service.cue(assetName, this);
// Add a mapping from token back to the controller that owns it.
controllerMap.put(token, controller);
return token;
}
/**
* Invoked by the audio service when the asset has finished
* playing. Calls the controller's {@link Controller#onFinished} method.
*/
@Override
public void onAudioPlayed(int audioToken) {
Controller controller = controllerMap.get(audioToken);
if (controller == null) {
throw new IllegalStateException("No controller for token " + audioToken);
}
controller.onFinished(audioToken);
}
private void validateAsset(String assetName) {
if (assetName == null) {
throw new NullPointerException();
}
}
}