1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 Polymer('audio-player', {
11 audioController: null,
15 // Attributes of the element (lower characters only).
16 // These values must be used only to data binding and shouldn't be assigned
17 // any value nowhere except in the handler.
34 * Model object of the Audio Player.
35 * @type {AudioPlayerModel}
40 * Initializes an element. This method is called automatically when the
44 this.audioController = this.$.audioController;
45 this.audioElement = this.$.audio;
46 this.trackList = this.$.trackList;
48 this.addEventListener('keydown', this.onKeyDown_.bind(this));
50 this.audioElement.volume = 0; // Temporary initial volume.
51 this.audioElement.addEventListener('ended', this.onAudioEnded.bind(this));
52 this.audioElement.addEventListener('error', this.onAudioError.bind(this));
54 var onAudioStatusUpdatedBound = this.onAudioStatusUpdate_.bind(this);
55 this.audioElement.addEventListener('timeupdate', onAudioStatusUpdatedBound);
56 this.audioElement.addEventListener('ended', onAudioStatusUpdatedBound);
57 this.audioElement.addEventListener('play', onAudioStatusUpdatedBound);
58 this.audioElement.addEventListener('pause', onAudioStatusUpdatedBound);
59 this.audioElement.addEventListener('suspend', onAudioStatusUpdatedBound);
60 this.audioElement.addEventListener('abort', onAudioStatusUpdatedBound);
61 this.audioElement.addEventListener('error', onAudioStatusUpdatedBound);
62 this.audioElement.addEventListener('emptied', onAudioStatusUpdatedBound);
63 this.audioElement.addEventListener('stalled', onAudioStatusUpdatedBound);
67 * Registers handlers for changing of external variables
70 'trackList.currentTrackIndex': 'onCurrentTrackIndexChanged',
71 'audioController.playing': 'onControllerPlayingChanged',
72 'audioController.time': 'onControllerTimeChanged',
73 'model.volume': 'onVolumeChanged',
77 * Invoked when trackList.currentTrackIndex is changed.
78 * @param {number} oldValue old value.
79 * @param {number} newValue new value.
81 onCurrentTrackIndexChanged: function(oldValue, newValue) {
82 var currentTrackUrl = '';
84 if (oldValue != newValue) {
85 var currentTrack = this.trackList.getCurrentTrack();
86 if (currentTrack && currentTrack.url != this.audioElement.src) {
87 this.audioElement.src = currentTrack.url;
88 currentTrackUrl = this.audioElement.src;
89 if (this.audioController.playing)
90 this.audioElement.play();
94 // The attributes may be being watched, so we change it at the last.
95 this.currenttrackurl = currentTrackUrl;
99 * Invoked when audioController.playing is changed.
100 * @param {boolean} oldValue old value.
101 * @param {boolean} newValue new value.
103 onControllerPlayingChanged: function(oldValue, newValue) {
104 this.playing = newValue;
107 if (!this.audioElement.src) {
108 var currentTrack = this.trackList.getCurrentTrack();
109 if (currentTrack && currentTrack.url != this.audioElement.src) {
110 this.audioElement.src = currentTrack.url;
114 if (this.audioElement.src) {
115 this.currenttrackurl = this.audioElement.src;
116 this.audioElement.play();
121 // When the new status is "stopped".
122 this.cancelAutoAdvance_();
123 this.audioElement.pause();
124 this.currenttrackurl = '';
125 this.lastAudioUpdateTime_ = null;
129 * Invoked when audioController.volume is changed.
130 * @param {number} oldValue old value.
131 * @param {number} newValue new value.
133 onVolumeChanged: function(oldValue, newValue) {
134 this.audioElement.volume = newValue / 100;
138 * Invoked when the model changed.
139 * @param {AudioPlayerModel} oldValue Old Value.
140 * @param {AudioPlayerModel} newValue New Value.
142 modelChanged: function(oldValue, newValue) {
143 this.trackList.model = newValue;
144 this.audioController.model = newValue;
146 // Invoke the handler manually.
147 this.onVolumeChanged(0, newValue.volume);
151 * Invoked when audioController.time is changed.
152 * @param {number} oldValue old time (in ms).
153 * @param {number} newValue new time (in ms).
155 onControllerTimeChanged: function(oldValue, newValue) {
156 // Ignores updates from the audio element.
157 if (this.lastAudioUpdateTime_ === newValue)
160 if (this.audioElement.readyState !== 0)
161 this.audioElement.currentTime = this.audioController.time / 1000;
165 * Invoked when the next button in the controller is clicked.
166 * This handler is registered in the 'on-click' attribute of the element.
168 onControllerNextClicked: function() {
169 this.advance_(true /* forward */, true /* repeat */);
173 * Invoked when the previous button in the controller is clicked.
174 * This handler is registered in the 'on-click' attribute of the element.
176 onControllerPreviousClicked: function() {
177 this.advance_(false /* forward */, true /* repeat */);
181 * Invoked when the playback in the audio element is ended.
182 * This handler is registered in this.ready().
184 onAudioEnded: function() {
186 this.advance_(true /* forward */, this.model.repeat);
190 * Invoked when the playback in the audio element gets error.
191 * This handler is registered in this.ready().
193 onAudioError: function() {
194 this.scheduleAutoAdvance_(true /* forward */, this.model.repeat);
198 * Invoked when the time of playback in the audio element is updated.
199 * This handler is registered in this.ready().
202 onAudioStatusUpdate_: function() {
203 this.audioController.time =
204 (this.lastAudioUpdateTime_ = this.audioElement.currentTime * 1000);
205 this.audioController.duration = this.audioElement.duration * 1000;
206 this.audioController.playing = !this.audioElement.paused;
210 * Invoked when receiving a request to replay the current music from the track
213 onReplayCurrentTrack: function() {
214 // Changes the current time back to the beginning, regardless of the current
215 // status (playing or paused).
216 this.audioElement.currentTime = 0;
217 this.audioController.time = 0;
221 * Goes to the previous or the next track.
222 * @param {boolean} forward True if next, false if previous.
223 * @param {boolean} repeat True if repeat-mode is enabled. False otherwise.
226 advance_: function(forward, repeat) {
227 this.cancelAutoAdvance_();
229 var nextTrackIndex = this.trackList.getNextTrackIndex(forward, true);
230 var isNextTrackAvailable =
231 (this.trackList.getNextTrackIndex(forward, repeat) !== -1);
233 this.audioController.playing = isNextTrackAvailable;
235 // If there is only a single file in the list, 'currentTrackInde' is not
236 // changed and the handler is not invoked. Instead, plays here.
237 // TODO(yoshiki): clean up the code around here.
238 if (isNextTrackAvailable &&
239 this.trackList.currentTrackIndex == nextTrackIndex) {
240 this.audioElement.play();
243 this.trackList.currentTrackIndex = nextTrackIndex;
245 Platform.performMicrotaskCheckpoint();
249 * Timeout ID of auto advance. Used internally in scheduleAutoAdvance_() and
250 * cancelAutoAdvance_().
254 autoAdvanceTimer_: null,
257 * Schedules automatic advance to the next track after a timeout.
258 * @param {boolean} forward True if next, false if previous.
259 * @param {boolean} repeat True if repeat-mode is enabled. False otherwise.
262 scheduleAutoAdvance_: function(forward, repeat) {
263 this.cancelAutoAdvance_();
264 var currentTrackIndex = this.currentTrackIndex;
266 var timerId = setTimeout(
268 // If the other timer is scheduled, do nothing.
269 if (this.autoAdvanceTimer_ !== timerId)
272 this.autoAdvanceTimer_ = null;
274 // If the track has been changed since the advance was scheduled, do
276 if (this.currentTrackIndex !== currentTrackIndex)
279 // We are advancing only if the next track is not known to be invalid.
280 // This prevents an endless auto-advancing in the case when all tracks
281 // are invalid (we will only visit each track once).
282 this.advance_(forward, repeat, true /* only if valid */);
286 this.autoAdvanceTimer_ = timerId;
290 * Cancels the scheduled auto advance.
293 cancelAutoAdvance_: function() {
294 if (this.autoAdvanceTimer_) {
295 clearTimeout(this.autoAdvanceTimer_);
296 this.autoAdvanceTimer_ = null;
301 * The index of the current track.
302 * If the list has no tracks, the value must be -1.
306 get currentTrackIndex() {
307 return this.trackList.currentTrackIndex;
309 set currentTrackIndex(value) {
310 this.trackList.currentTrackIndex = value;
314 * The list of the tracks in the playlist.
316 * When it changed, current operation including playback is stopped and
317 * restarts playback with new tracks if necessary.
319 * @type {Array.<AudioPlayer.TrackInfo>}
322 return this.trackList ? this.trackList.tracks : null;
325 if (this.trackList.tracks === tracks)
328 this.cancelAutoAdvance_();
330 this.trackList.tracks = tracks;
331 var currentTrack = this.trackList.getCurrentTrack();
332 if (currentTrack && currentTrack.url != this.audioElement.src) {
333 this.audioElement.src = currentTrack.url;
334 this.audioElement.play();
339 * Invoked when the audio player is being unloaded.
341 onPageUnload: function() {
342 this.audioElement.src = ''; // Hack to prevent crashing.
346 * Invoked when the 'keydown' event is fired.
347 * @param {Event} event The event object.
349 onKeyDown_: function(event) {
350 switch (event.keyIdentifier) {
352 if (this.audioController.volumeSliderShown && this.model.volume < 100)
353 this.model.volume += 1;
356 if (this.audioController.volumeSliderShown && this.model.volume > 0)
357 this.model.volume -= 1;
360 if (this.audioController.volumeSliderShown && this.model.volume < 91)
361 this.model.volume += 10;
364 if (this.audioController.volumeSliderShown && this.model.volume > 9)
365 this.model.volume -= 10;
367 case 'MediaNextTrack':
368 this.onControllerNextClicked();
370 case 'MediaPlayPause':
371 var playing = this.audioController.playing;
372 this.onControllerPlayingChanged(playing, !playing);
374 case 'MediaPreviousTrack':
375 this.onControllerPreviousClicked();
378 // TODO: Define "Stop" behavior.