├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── bower.json ├── demo.gif ├── dist ├── .gitignore └── media-sequence.min.js ├── index.js ├── karma.conf.js ├── lib ├── core.js └── scheduler.js ├── package.json └── test ├── core.js └── fixture.ogg /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # Compiled binary addons (http://nodejs.org/api/addons.html) 20 | build/Release 21 | 22 | # Dependency directory 23 | # Deployed apps should consider commenting this line out: 24 | # see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git 25 | node_modules 26 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: '0.10' 3 | 4 | before_install: 5 | - "export DISPLAY=:99.0" 6 | - "sh -e /etc/init.d/xvfb start" 7 | 8 | before_script: 9 | - "npm install -g grunt-cli" 10 | - "rm -rf ${TRAVIS_BUILD_DIR}/node_modules/karma" 11 | - "cd ${TRAVIS_BUILD_DIR} && npm install https://github.com/karma-runner/karma/tarball/c071305b08f0dcb3cac1b9a04e6feefbbde13882" 12 | - "head -n30 node_modules/karma/lib/preprocessor.js" 13 | - "cd ${TRAVIS_BUILD_DIR}/node_modules/karma && npm install" 14 | - "grunt --gruntfile ${TRAVIS_BUILD_DIR}/node_modules/karma/Gruntfile.coffee build" 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # media-sequence 2 | 3 | > HTML5 media sequenced playback API: play one or multiple sequences of a same audio or video with plain JavaScript. 4 | 5 | ![](demo.gif?raw=1) 6 | 7 | # Installation 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
npmbowerold school
npm install --save media-sequencebower install --save media-sequencedownload zip file
25 | 26 | # Usage 27 | 28 | ```js 29 | var sequences = [{start: 0, end: 5}, {start: 12, end: 13}, {start: 21, end: 31}]; 30 | var sequencer = new MediaSequence(new Audio('path/to/audio.ogg'), sequences); 31 | 32 | sequencer.playAll(); 33 | ``` 34 | 35 | # API 36 | 37 | ## `new MediaSequence(el, sequences)` 38 | 39 | ## `sequencer.add(sequences)` 40 | 41 | Adds new sequences to the actual stack. 42 | 43 | ```js 44 | var sequencer = new MediaSequence(new Audio('path/to/audio.ogg')); 45 | 46 | sequencer.add([{ start: 0, end: 10 }, { start: 3, end: 6}]); 47 | sequencer.add([{ start: 11, end: 12 }]); 48 | ``` 49 | 50 | ## `sequencer.playAll()` 51 | 52 | Starts the playback of all the sequences in a row. 53 | 54 | ## `sequencer.playFrom(start, end)` 55 | 56 | Starts the playback from a `start` time and stops automatically at an `end` time. 57 | 58 | ```js 59 | var sequencer = new MediaSequence(new Audio('path/to/audio.ogg')); 60 | 61 | sequencer.playFrom(10, 12); // will play from 10 seconds to 12 seconds 62 | ``` 63 | 64 | ## `sequencer.playNext()` 65 | 66 | Plays the next consecutive sequence based on the current playback time. 67 | 68 | ```js 69 | var el = new Audio('path/to/audio.ogg'); 70 | var sequencer = new MediaSequence(el, sequences); 71 | 72 | el.currentTime = 12; 73 | sequencer.playNext(); // will play the next sequence starting after 12 seconds 74 | ``` 75 | 76 | ## `sequencer.getNext(referenceTime, options)` 77 | 78 | Returns the next sequence from a `referenceTime` numbered value. 79 | 80 | ```js 81 | var ms = new MediaSequencer(…, [{ start: 3, end: 5 }, { start: 12, end: 13 }]); 82 | 83 | ms.getNext(0); 84 | // { start: 3, end: 5 } 85 | 86 | ms.getNext(3); 87 | // { start: 12, end: 13 } 88 | ``` 89 | 90 | If the `options.overlap` value is set to `true`, the returned sequence is allowed to overlap: 91 | 92 | ```js 93 | var ms = new MediaSequencer(…, [{ start: 3, end: 5 }, {start: 3, end: 10 }, { start: 12, end: 13 }]); 94 | 95 | ms.getNext(3); 96 | // { start: 12, end: 13 } 97 | 98 | ms.getNext(3, { overlap: true }); 99 | // {start: 3, end: 5 } 100 | ``` 101 | 102 | # Licence 103 | 104 | > Copyright 2014 British Broadcasting Corporation 105 | > 106 | > Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 107 | > 108 | > http://www.apache.org/licenses/LICENSE-2.0 109 | > 110 | > Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "media-sequence", 3 | "version": "0.1.1", 4 | "homepage": "https://github.com/bbc/media-sequence", 5 | "authors": [ 6 | "Thomas Parisot " 7 | ], 8 | "description": "HTML5 media sequenced playback API: play one or multiple sequences of a same audio or video with plain JavaScript.", 9 | "main": "index.js", 10 | "moduleType": [ 11 | "globals" 12 | ], 13 | "keywords": [ 14 | "html5", 15 | "video", 16 | "audio", 17 | "media", 18 | "sequence", 19 | "sequences", 20 | "playback" 21 | ], 22 | "license": "Apache-2", 23 | "ignore": [ 24 | "**/.*", 25 | "node_modules", 26 | "bower_components", 27 | "test", 28 | "tests" 29 | ] 30 | } 31 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbc/media-sequence/8288173c42aebfceb8b2fb7777e09b11b3dfe15f/demo.gif -------------------------------------------------------------------------------- /dist/.gitignore: -------------------------------------------------------------------------------- 1 | *.* 2 | !media-sequence.min.js -------------------------------------------------------------------------------- /dist/media-sequence.min.js: -------------------------------------------------------------------------------- 1 | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.MediaSequence=e()}}(function(){return function e(t,n,r){function i(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(s)return s(o,!0);throw new Error("Cannot find module '"+o+"'")}var c=n[o]={exports:{}};t[o][0].call(c.exports,function(e){var n=t[o][1][e];return i(n?n:e)},c,c.exports,e,t,n,r)}return n[o].exports}for(var s="function"==typeof require&&require,o=0;oe||Boolean(t.overlap)&&n.end>e});return n[0]||null},n.prototype.getMediaDuration=function(){return this.mediaElement.duration},n.prototype.seek=function(e){return this.mediaElement.currentTime=e,this},n.prototype.play=function(){return this.mediaElement.play(),this},n.prototype.pause=function(){return this.mediaElement.pause(),this},n.prototype.runScheduler=function(e){return this.scheduler&&this.scheduler.call(this.scheduler,e)},n.prototype.playAll=function(){var e=this,t=this.getNext(0);if(!t)throw new RangeError("There is no sequence to play.");return this.scheduler=new s(t,function(t){if(!(t=0==!1)throw new TypeError("startTime should be a valid HTMLMediaElement time value.");if(e>=this.getMediaDuration())throw new RangeError("startTime value should be lower than its duration.");if(e>=t)throw new RangeError("endTime should be further in time that the startTime value.");return this.scheduler=new s(t,function(e){return e>=this.getEndTime()?(n.pause(),n.emit("playfrom.end",this.getEndTime(),n),!0):void 0}),this.seek(e),this.play()},n.prototype.playNext=function(){var e=this.getNext(this.mediaElement.currentTime);return e&&(this.scheduler?(this.emit("playnext.sequence",e),this.scheduler.postponeToSequenceEnd(e),this.seek(e.start),this.play()):this.playFrom(e.start,e.end)),this},t.exports=n},{"./scheduler.js":3,events:4,util:8}],3:[function(e,t){"use strict";t.exports=function(e,t){return function(){"number"==typeof e&&(e={start:null,end:e});var n=e,r=e.end,i=function(e){var n=t.call(this,e.detail?e.detail.currentTime:e.target.currentTime);n===!0&&(t=function(){})};return i.getEndTime=function(){return r},i.getSequence=function(){return n},i.postponeTo=function(e){r=e},i.postponeToSequenceStart=function(e){n=e,this.postponeTo(e.start)},i.postponeToSequenceEnd=function(e){n=e,this.postponeTo(e.end)},i}()}},{}],4:[function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function i(e){return"number"==typeof e}function s(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!i(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,i,u,a,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||s(this._events.error)&&!this._events.error.length))throw t=arguments[1],t instanceof Error?t:TypeError('Uncaught, unspecified "error" event.');if(n=this._events[e],o(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:for(i=arguments.length,u=new Array(i-1),a=1;i>a;a++)u[a-1]=arguments[a];n.apply(this,u)}else if(s(n)){for(i=arguments.length,u=new Array(i-1),a=1;i>a;a++)u[a-1]=arguments[a];for(c=n.slice(),i=c.length,a=0;i>a;a++)c[a].apply(this,u)}return!0},n.prototype.addListener=function(e,t){var i;if(!r(t))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t),this._events[e]?s(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,s(this._events[e])&&!this._events[e].warned){var i;i=o(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,i&&i>0&&this._events[e].length>i&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())}return this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),i||(i=!0,t.apply(this,arguments))}if(!r(t))throw TypeError("listener must be a function");var i=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,i,o,u;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],o=n.length,i=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(s(n)){for(u=o;u-->0;)if(n[u]===t||n[u].listener&&n[u].listener===t){i=u;break}if(0>i)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],r(n))this.removeListener(e,n);else for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.listenerCount=function(e,t){var n;return n=e._events&&e._events[t]?r(e._events[t])?1:e._events[t].length:0}},{}],5:[function(e,t){t.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},{}],6:[function(e,t){function n(){}var r=t.exports={};r.nextTick=function(){var e="undefined"!=typeof window&&window.setImmediate,t="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(e)return function(e){return window.setImmediate(e)};if(t){var n=[];return window.addEventListener("message",function(e){var t=e.source;if((t===window||null===t)&&"process-tick"===e.data&&(e.stopPropagation(),n.length>0)){var r=n.shift();r()}},!0),function(e){n.push(e),window.postMessage("process-tick","*")}}return function(e){setTimeout(e,0)}}(),r.title="browser",r.browser=!0,r.env={},r.argv=[],r.on=n,r.addListener=n,r.once=n,r.off=n,r.removeListener=n,r.removeAllListeners=n,r.emit=n,r.binding=function(){throw new Error("process.binding is not supported")},r.cwd=function(){return"/"},r.chdir=function(){throw new Error("process.chdir is not supported")}},{}],7:[function(e,t){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],8:[function(e,t,n){(function(t,r){function i(e,t){var r={seen:[],stylize:o};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),m(t)?r.showHidden=t:t&&n._extend(r,t),_(r.showHidden)&&(r.showHidden=!1),_(r.depth)&&(r.depth=2),_(r.colors)&&(r.colors=!1),_(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=s),a(r,e,r.depth)}function s(e,t){var n=i.styles[t];return n?"["+i.colors[n][0]+"m"+e+"["+i.colors[n][1]+"m":e}function o(e){return e}function u(e){var t={};return e.forEach(function(e){t[e]=!0}),t}function a(e,t,r){if(e.customInspect&&t&&S(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return w(i)||(i=a(e,i,r)),i}var s=c(e,t);if(s)return s;var o=Object.keys(t),m=u(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(t)),T(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return l(t);if(0===o.length){if(S(t)){var v=t.name?": "+t.name:"";return e.stylize("[Function"+v+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(L(t))return e.stylize(Date.prototype.toString.call(t),"date");if(T(t))return l(t)}var y="",g=!1,b=["{","}"];if(d(t)&&(g=!0,b=["[","]"]),S(t)){var _=t.name?": "+t.name:"";y=" [Function"+_+"]"}if(E(t)&&(y=" "+RegExp.prototype.toString.call(t)),L(t)&&(y=" "+Date.prototype.toUTCString.call(t)),T(t)&&(y=" "+l(t)),0===o.length&&(!g||0==t.length))return b[0]+y+b[1];if(0>r)return E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var x;return x=g?f(e,t,r,m,o):o.map(function(n){return p(e,t,r,m,n,g)}),e.seen.pop(),h(x,y,b)}function c(e,t){if(_(t))return e.stylize("undefined","undefined");if(w(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return g(t)?e.stylize(""+t,"number"):m(t)?e.stylize(""+t,"boolean"):v(t)?e.stylize("null","null"):void 0}function l(e){return"["+Error.prototype.toString.call(e)+"]"}function f(e,t,n,r,i){for(var s=[],o=0,u=t.length;u>o;++o)s.push(M(t,String(o))?p(e,t,n,r,String(o),!0):"");return i.forEach(function(i){i.match(/^\d+$/)||s.push(p(e,t,n,r,i,!0))}),s}function p(e,t,n,r,i,s){var o,u,c;if(c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]},c.get?u=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(u=e.stylize("[Setter]","special")),M(r,i)||(o="["+i+"]"),u||(e.seen.indexOf(c.value)<0?(u=v(n)?a(e,c.value,null):a(e,c.value,n-1),u.indexOf("\n")>-1&&(u=s?u.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+u.split("\n").map(function(e){return" "+e}).join("\n"))):u=e.stylize("[Circular]","special")),_(o)){if(s&&i.match(/^\d+$/))return u;o=JSON.stringify(""+i),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+u}function h(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function d(e){return Array.isArray(e)}function m(e){return"boolean"==typeof e}function v(e){return null===e}function y(e){return null==e}function g(e){return"number"==typeof e}function w(e){return"string"==typeof e}function b(e){return"symbol"==typeof e}function _(e){return void 0===e}function E(e){return x(e)&&"[object RegExp]"===O(e)}function x(e){return"object"==typeof e&&null!==e}function L(e){return x(e)&&"[object Date]"===O(e)}function T(e){return x(e)&&("[object Error]"===O(e)||e instanceof Error)}function S(e){return"function"==typeof e}function j(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function O(e){return Object.prototype.toString.call(e)}function q(e){return 10>e?"0"+e.toString(10):e.toString(10)}function z(){var e=new Date,t=[q(e.getHours()),q(e.getMinutes()),q(e.getSeconds())].join(":");return[e.getDate(),D[e.getMonth()],t].join(" ")}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var A=/%[sdj%]/g;n.format=function(e){if(!w(e)){for(var t=[],n=0;n=s)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}}),u=r[n];s>n;u=r[++n])o+=v(u)||!x(u)?" "+u:" "+i(u);return o},n.deprecate=function(e,i){function s(){if(!o){if(t.throwDeprecation)throw new Error(i);t.traceDeprecation?console.trace(i):console.error(i),o=!0}return e.apply(this,arguments)}if(_(r.process))return function(){return n.deprecate(e,i).apply(this,arguments)};if(t.noDeprecation===!0)return e;var o=!1;return s};var N,k={};n.debuglog=function(e){if(_(N)&&(N=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!k[e])if(new RegExp("\\b"+e+"\\b","i").test(N)){var r=t.pid;k[e]=function(){var t=n.format.apply(n,arguments);console.error("%s %d: %s",e,r,t)}}else k[e]=function(){};return k[e]},n.inspect=i,i.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},i.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},n.isArray=d,n.isBoolean=m,n.isNull=v,n.isNullOrUndefined=y,n.isNumber=g,n.isString=w,n.isSymbol=b,n.isUndefined=_,n.isRegExp=E,n.isObject=x,n.isDate=L,n.isError=T,n.isFunction=S,n.isPrimitive=j,n.isBuffer=e("./support/isBuffer");var D=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];n.log=function(){console.log("%s - %s",z(),n.format.apply(n,arguments))},n.inherits=e("inherits"),n._extend=function(e,t){if(!t||!x(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}}).call(this,e("FWaASH"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":7,FWaASH:6,inherits:5}]},{},[1])(1)}); 2 | //# sourceMappingURL=./media-sequence.min.js.map -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = require('./lib/core.js'); -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration 2 | // Generated on Tue Jun 17 2014 16:46:08 GMT+0100 (BST) 3 | 4 | module.exports = function(config) { 5 | config.set({ 6 | 7 | // base path that will be used to resolve all patterns (eg. files, exclude) 8 | basePath: './', 9 | 10 | 11 | // frameworks to use 12 | // available frameworks: https://npmjs.org/browse/keyword/karma-adapter 13 | frameworks: ['browserify', 'mocha', 'sinon-chai'], 14 | 15 | 16 | // list of files / patterns to load in the browser 17 | files: [ 18 | 'index.js', 19 | 'lib/**/*.js', 20 | 'test/**/*.js', 21 | { pattern: 'test/*.{ogg,mp3}', watched: false, included: false, served: true } 22 | ], 23 | 24 | 25 | // list of files to exclude 26 | exclude: [ 27 | ], 28 | 29 | 30 | // preprocess matching files before serving them to the browser 31 | // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor 32 | preprocessors: { 33 | 'index.js': 'browserify', 34 | '{test,lib}/**/*.js': 'browserify' 35 | }, 36 | 37 | browserify: { 38 | debug: true 39 | }, 40 | 41 | // test results reporter to use 42 | // possible values: 'dots', 'progress' 43 | // available reporters: https://npmjs.org/browse/keyword/karma-reporter 44 | reporters: ['progress'], 45 | 46 | 47 | // web server port 48 | port: 9876, 49 | 50 | 51 | // enable / disable colors in the output (reporters and logs) 52 | colors: true, 53 | 54 | 55 | // level of logging 56 | // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG 57 | logLevel: config.LOG_INFO, 58 | 59 | 60 | // enable / disable watching file and executing tests whenever any file changes 61 | autoWatch: true, 62 | 63 | 64 | // start these browsers 65 | // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher 66 | browsers: Boolean(process.env.CI) ? ['Firefox'] : ['Chrome'], 67 | 68 | 69 | // Continuous Integration mode 70 | // if true, Karma captures browsers, runs the tests and exits 71 | singleRun: Boolean(process.env.CI) 72 | }); 73 | }; 74 | -------------------------------------------------------------------------------- /lib/core.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var EventEmitter = require('events').EventEmitter; 4 | var inherits = require('util').inherits; 5 | var Scheduler = require('./scheduler.js'); 6 | 7 | /** 8 | * 9 | * @param el 10 | * @param sequences 11 | * @constructor 12 | */ 13 | function MediaSequence (el, sequences) { 14 | if ((el instanceof HTMLMediaElement) === false) { 15 | throw new TypeError('The element argument should be an instance of HTMLMediaElement.'); 16 | } 17 | 18 | this.mediaElement = el; 19 | 20 | this.scheduler = null; 21 | 22 | this.mediaElement.addEventListener('timeupdate', this.runScheduler.bind(this)); 23 | 24 | this.sequences = []; 25 | 26 | this.add(sequences || []); 27 | } 28 | 29 | inherits(MediaSequence, EventEmitter); 30 | 31 | /** 32 | * 33 | * @param sequences 34 | */ 35 | MediaSequence.prototype.add = function (sequences) { 36 | if (!Array.isArray(sequences)) { 37 | throw new TypeError('The sequences argument should be an array of {start, end} objects.') 38 | } 39 | 40 | this.sequences = this.sequences 41 | .concat(sequences) 42 | .sort(function ascByStartTimeAndLength(a, b){ 43 | return (a.start - b.start) || (a.end - b.end); 44 | }); 45 | 46 | return this; 47 | }; 48 | 49 | /** 50 | * Returns the next sequence in time after the current one. 51 | * 52 | * @param referenceTime {Number} 53 | * @returns {Object|null} 54 | */ 55 | MediaSequence.prototype.getNext = function getNextSequence(referenceTime, options){ 56 | options = options || {}; 57 | 58 | var sequences = this.sequences.filter(function unionFilter(sequence){ 59 | return sequence.start > referenceTime || (Boolean(options.overlap) && sequence.end > referenceTime); 60 | }); 61 | 62 | return sequences[0] || null; 63 | }; 64 | 65 | /** 66 | * Mostly here to enables stubbing. 67 | * 68 | * @api 69 | * @returns {Number} 70 | */ 71 | MediaSequence.prototype.getMediaDuration = function getMediaDuration () { 72 | return this.mediaElement.duration; 73 | }; 74 | 75 | MediaSequence.prototype.seek = function seekMediaPosition(time){ 76 | this.mediaElement.currentTime = time; 77 | 78 | return this; 79 | }; 80 | 81 | /** 82 | * 83 | * @returns {MediaSequence} 84 | */ 85 | MediaSequence.prototype.play = function play () { 86 | this.mediaElement.play(); 87 | 88 | return this; 89 | }; 90 | 91 | /** 92 | * 93 | * @returns {MediaSequence} 94 | */ 95 | MediaSequence.prototype.pause = function pause () { 96 | this.mediaElement.pause(); 97 | 98 | return this; 99 | }; 100 | 101 | MediaSequence.prototype.runScheduler = function runScheduler(event){ 102 | return this.scheduler && this.scheduler.call(this.scheduler, event); 103 | }; 104 | 105 | /** 106 | * 107 | * @returns {MediaSequence} 108 | */ 109 | MediaSequence.prototype.playAll = function playAll () { 110 | var selfie = this; 111 | var firstSequence = this.getNext(0); 112 | 113 | if (!firstSequence) { 114 | throw new RangeError('There is no sequence to play.'); 115 | } 116 | 117 | this.scheduler = new Scheduler(firstSequence, function onTimeupdate(currentTime){ 118 | // the current sequence is not over yet, skip the beat. 119 | if (currentTime < this.getSequence().end) { 120 | return; 121 | } 122 | 123 | var nextSequence = selfie.getNext(currentTime, { overlap: true }); 124 | 125 | if (nextSequence === null){ 126 | selfie.pause(); 127 | selfie.emit('playall.end', selfie); 128 | 129 | return true; 130 | } 131 | 132 | // the actual sequence is over but the next sequence overlaps with it 133 | // we want to postpone the scheduler to the end of the next sequence 134 | if (nextSequence.start <= this.getEndTime()){ 135 | selfie.emit('playall.postpone', nextSequence); 136 | this.postponeToSequenceEnd(nextSequence); 137 | return; 138 | } 139 | 140 | // otherwise we jump to the beginning of the next sequence 141 | // and schedule a new end time 142 | selfie.emit('playall.sequence', nextSequence); 143 | this.postponeToSequenceStart(nextSequence); 144 | selfie.seek(nextSequence.start); 145 | }); 146 | 147 | this.seek(firstSequence.start); 148 | return this.play(); 149 | }; 150 | 151 | /** 152 | * Starts a playback from `startTime` and ends at `endTime` 153 | * 154 | * @param startTime {Number} 155 | * @param endTime {Number=} 156 | * @returns {MediaSequence} 157 | */ 158 | MediaSequence.prototype.playFrom = function playFrom (startTime, endTime) { 159 | var selfie = this; 160 | endTime = endTime || this.getMediaDuration(); 161 | 162 | if ((startTime >= 0) === false) { 163 | throw new TypeError('startTime should be a valid HTMLMediaElement time value.'); 164 | } 165 | 166 | if (startTime >= this.getMediaDuration()) { 167 | throw new RangeError('startTime value should be lower than its duration.'); 168 | } 169 | 170 | if (endTime <= startTime) { 171 | throw new RangeError('endTime should be further in time that the startTime value.'); 172 | } 173 | 174 | this.scheduler = new Scheduler(endTime, function onTimeupdate(currentTime){ 175 | if (currentTime >= this.getEndTime()) { 176 | selfie.pause(); 177 | selfie.emit('playfrom.end', this.getEndTime(), selfie); 178 | 179 | return true; 180 | } 181 | }); 182 | 183 | this.seek(startTime); 184 | 185 | return this.play(); 186 | }; 187 | 188 | 189 | /** 190 | * 191 | * @param referenceTime 192 | * @returns {MediaSequence} 193 | */ 194 | MediaSequence.prototype.playNext = function playNext () { 195 | var nextSequence = this.getNext(this.mediaElement.currentTime); 196 | 197 | if (nextSequence) { 198 | if (this.scheduler) { 199 | this.emit('playnext.sequence', nextSequence); 200 | this.scheduler.postponeToSequenceEnd(nextSequence); 201 | this.seek(nextSequence.start); 202 | this.play(); 203 | } 204 | else { 205 | this.playFrom(nextSequence.start, nextSequence.end); 206 | } 207 | } 208 | 209 | return this; 210 | }; 211 | 212 | module.exports = MediaSequence; -------------------------------------------------------------------------------- /lib/scheduler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = function(sequence, onTimeupdate){ 4 | return (function () { 5 | // backward compatibility 6 | if (typeof sequence === 'number'){ 7 | sequence = { start: null, end: sequence }; 8 | } 9 | 10 | var currentSequence = sequence; 11 | var endTime = sequence.end; 12 | 13 | var Scheduler = function Scheduler (event){ 14 | var result = onTimeupdate.call(this, event.detail ? event.detail.currentTime : event.target.currentTime); 15 | 16 | if (result === true){ 17 | onTimeupdate = function(){}; 18 | } 19 | }; 20 | 21 | Scheduler.getEndTime = function getSchedulerEndTime(){ 22 | return endTime; 23 | }; 24 | 25 | Scheduler.getSequence = function getSchedulerSequence(){ 26 | return currentSequence; 27 | }; 28 | 29 | Scheduler.postponeTo = function postponeTo(newEndTime){ 30 | endTime = newEndTime; 31 | }; 32 | 33 | Scheduler.postponeToSequenceStart = function postponeToSequenceStart(sequence){ 34 | currentSequence = sequence; 35 | this.postponeTo(sequence.start); 36 | }; 37 | 38 | Scheduler.postponeToSequenceEnd = function postponeToSequenceEnd(sequence){ 39 | currentSequence = sequence; 40 | this.postponeTo(sequence.end); 41 | }; 42 | 43 | return Scheduler; 44 | })(); 45 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "media-sequence", 3 | "version": "0.1.1", 4 | "description": "HTML5 media sequenced playback API: play one or multiple sequences of a same audio or video with plain JavaScript.", 5 | "main": "./index.js", 6 | "scripts": { 7 | "test": "./node_modules/karma/bin/karma start", 8 | "build": "npm run build-browser && npm run build-compress", 9 | "build-browser": "browserify -s MediaSequence -r ./index.js > dist/media-sequence.js", 10 | "build-compress": "uglifyjs dist/media-sequence.js --source-map dist/media-sequence.min.js.map --source-map-root ../ --source-map-url ./media-sequence.min.js.map --compress --screw-ie8 --mangle > dist/media-sequence.min.js" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git@github.com:bbc/media-sequence.git" 15 | }, 16 | "keywords": [ 17 | "html5", 18 | "video", 19 | "audio", 20 | "sequence", 21 | "playback", 22 | "sequenced" 23 | ], 24 | "author": "Thomas Parisot (https://oncletom.io)", 25 | "license": "Apache-2", 26 | "bugs": { 27 | "url": "https://github.com/bbc/media-sequence/issues" 28 | }, 29 | "homepage": "https://github.com/bbc/media-sequence", 30 | "devDependencies": { 31 | "browserify": "^4.1.11", 32 | "chai": "^1.9.1", 33 | "karma": "^0.12.16", 34 | "karma-bro": "^0.5.0", 35 | "karma-chai": "^0.1.0", 36 | "karma-chrome-launcher": "^0.1.4", 37 | "karma-firefox-launcher": "^0.1.3", 38 | "karma-mocha": "^0.1.4", 39 | "karma-phantomjs-launcher": "^0.1.4", 40 | "karma-sinon": "^1.0.3", 41 | "karma-sinon-chai": "^0.1.6", 42 | "mocha": "^1.20.1", 43 | "sinon": "^1.10.2", 44 | "uglify-js": "^2.4.14", 45 | "watchify": "^0.10.2" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /test/core.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var MediaSequence = require('../index.js'); 4 | var Scheduler = require('../lib/scheduler.js'); 5 | var sinon = require('sinon'); 6 | 7 | describe('MediaSequence', function(){ 8 | var ms, sandbox, playStub, seekStub; 9 | 10 | beforeEach(function(done){ 11 | var mediaElement = new Audio('base/test/fixture.ogg'); 12 | mediaElement.preload = 'auto'; 13 | mediaElement.muted = true; 14 | 15 | sandbox = sinon.sandbox.create(); 16 | ms = new MediaSequence(mediaElement); 17 | 18 | playStub = sandbox.stub(ms, 'play'); 19 | seekStub = sandbox.stub(ms, 'seek'); 20 | 21 | mediaElement.addEventListener('canplaythrough', function(){ 22 | sandbox.stub(ms, 'getMediaDuration').returns(30); 23 | 24 | done(); 25 | }); 26 | }); 27 | 28 | afterEach(function(){ 29 | sandbox.restore(); 30 | }); 31 | 32 | describe('playFrom', function(){ 33 | it('should raise an error if the end time is further than the duration', function(){ 34 | expect(function(){ 35 | ms.playFrom(10000000, 12000000); 36 | }).to.throw(RangeError); 37 | }); 38 | 39 | it('should raise an error if the startTime is not a valid time value', function (){ 40 | expect(function(){ 41 | ms.playFrom(NaN); 42 | }).to.throw(TypeError); 43 | }); 44 | 45 | it('should raise an error if the startTime is not a valid time value', function (){ 46 | expect(function(){ 47 | ms.playFrom(7, 5); 48 | }).to.throw(/^endTime/); 49 | }); 50 | 51 | it('should request to change the playback to the requested position', function (){ 52 | ms.playFrom(10, 12); 53 | 54 | expect(seekStub).to.have.been.calledWithExactly(10); 55 | }); 56 | 57 | it('should also start the playback', function (){ 58 | ms.playFrom(10, 12); 59 | 60 | expect(playStub).to.have.been.calledOnce; 61 | }); 62 | 63 | it('should trigger a playfrom.end when the endTime is reached', function(done){ 64 | ms.on('playfrom.end', function(endTime, instance){ 65 | expect(endTime).to.equal(12); 66 | 67 | done(); 68 | }); 69 | 70 | ms.playFrom(10, 12); 71 | ms.mediaElement.dispatchEvent(new CustomEvent('timeupdate', { detail: { currentTime: 12 } })); 72 | }); 73 | 74 | it('should pause the playback by default when the endTime is reached', function(done){ 75 | var pauseStub = sandbox.stub(ms, 'pause'); 76 | ms.playFrom(10, 12); 77 | 78 | ms.mediaElement.dispatchEvent(new CustomEvent('timeupdate', { detail: { currentTime: 12 } })); 79 | 80 | setTimeout(function(){ 81 | expect(pauseStub).to.have.been.calledOnce; 82 | done(); 83 | }, 0); 84 | }); 85 | }); 86 | 87 | describe('getNext', function(){ 88 | beforeEach(function(){ 89 | ms.add([ 90 | { start: 20, end: 25 }, 91 | { start: 12, end: 16 }, 92 | { start: 0, end: 5 }, 93 | { start: 12, end: 18 }, 94 | { start: 10, end: 15 } 95 | ]); 96 | }); 97 | 98 | it('should select a sequence starting at 10 if the reference time is 0', function(){ 99 | expect(ms.getNext(0)).to.have.property('start', 10); 100 | }); 101 | 102 | it('should select the next sequence starting at 12 if the reference time coincides with the beginning of a sequence starting at 10', function(){ 103 | expect(ms.getNext(10)).to.have.property('start', 12); 104 | }); 105 | 106 | it('should select the next sequence starting at 12 if the reference time is included in a sequence starting at 10', function(){ 107 | expect(ms.getNext(11)).to.have.property('start', 12); 108 | }); 109 | 110 | it('should select the closest ending sequence for an equal start time of 12', function(){ 111 | expect(ms.getNext(11)).to.have.property('end', 16); 112 | }); 113 | 114 | it('should return the closest overlapping sequence', function(){ 115 | expect(ms.getNext(12, { overlap: true })).to.have.property('end', 15) 116 | }); 117 | 118 | it('should return the closest overlapping sequence', function(){ 119 | expect(ms.getNext(15, { overlap: true })).to.have.property('end', 16) 120 | }); 121 | 122 | it('should not return any sequence for a start time greater or equal to 20', function(){ 123 | expect(ms.getNext(20)).to.be.a('null'); 124 | }); 125 | }); 126 | 127 | describe('playAll', function(){ 128 | var scheduler; 129 | 130 | beforeEach(function(){ 131 | scheduler = new Scheduler(0, sinon.spy()); 132 | ms.add([ 133 | { start: 10, end: 15 }, 134 | { start: 12, end: 14 }, 135 | { start: 12, end: 18 }, 136 | { start: 20, end: 25 } 137 | ]); 138 | }); 139 | 140 | it('should seek and play the first sequence starting at 10', function(){ 141 | ms.playAll(); 142 | 143 | expect(seekStub).to.be.calledWith(10); 144 | expect(playStub).to.be.calledOnce; 145 | }); 146 | 147 | it('should then postpone from 15 to 18, as of the next ending segment', function(done){ 148 | ms.on('playall.postpone', function(sequence){ 149 | expect(sequence).to.have.property('end', 18); 150 | 151 | done(); 152 | }); 153 | 154 | ms.playAll(); 155 | ms.mediaElement.dispatchEvent(new CustomEvent('timeupdate', { detail: { currentTime: 15 } })); 156 | }); 157 | 158 | it('should then play the sequence starting at 20', function(done){ 159 | ms.on('playall.sequence', function(sequence){ 160 | expect(sequence).to.have.property('start', 20); 161 | 162 | setTimeout(function(){ 163 | expect(seekStub.lastCall).to.have.been.calledWith(20); 164 | done(); 165 | }, 0); 166 | }); 167 | 168 | ms.playAll(); 169 | ms.mediaElement.dispatchEvent(new CustomEvent('timeupdate', { detail: { currentTime: 18 } })); 170 | }); 171 | 172 | it('should stop the playback once reached 25', function(done){ 173 | var spy = sandbox.spy(ms, 'pause'); 174 | 175 | ms.on('playall.end', function(){ 176 | expect(spy).to.have.been.calledOnce; 177 | done(); 178 | }); 179 | 180 | ms.playAll(); 181 | ms.mediaElement.dispatchEvent(new CustomEvent('timeupdate', { detail: { currentTime: 25 } })); 182 | }); 183 | }); 184 | }); 185 | 186 | -------------------------------------------------------------------------------- /test/fixture.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbc/media-sequence/8288173c42aebfceb8b2fb7777e09b11b3dfe15f/test/fixture.ogg --------------------------------------------------------------------------------