├── .github └── FUNDING.yml ├── LICENSE ├── README.md ├── admin └── admin.php ├── assets ├── native_audio.png ├── native_video.png ├── selecting_shortcode.png ├── sharing_excerpt.png ├── shortcode_usage.png ├── soundcloud_player.png ├── transcript_converter.png ├── transcript_converter_howto.png ├── transcript_converter_howto_customize.png ├── transcript_converter_interface.png ├── transcript_converter_markup.png └── upload_media.png ├── css └── share-this.css ├── hyperaudio.php ├── js ├── caption.js ├── converter.js ├── hyperaudio-lite.js └── velocity.js └── readme.txt /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hyperaudio Interactive Transcript for WordPress 2 | A WordPress plugin to display [Interactive Transcripts](https://en.wikipedia.org/wiki/Interactive_transcripts) 3 | 4 | Interactive Transcripts help make audio and video more accessible, easier to navigate, search, index and share. Some examples can be found here: [https://lab.hyperaud.io/mozfest2021/interviews/](https://lab.hyperaud.io/mozfest2021/interviews/) 5 | 6 | You can make Interactive Transcripts with the [Hyperaudio Lite Editor](https://github.com/hyperaudio/hyperaudio-lite-editor) 7 | 8 | ## Getting started 9 | 10 | 1. [Download the ZIP file](https://github.com/hyperaudio/wordpress-hyperaudio/archive/refs/heads/main.zip) from the GitHub repository. It's recommend you rename the ZIP file to the folder name you would like the plugin to appear in, usually `hyperaudio.zip`. 11 | 2. Install the plugin. Either: 12 | - Using the WordPress Admin 13 | 1. While logged into the target site, navigate to the **Plugins** page, usually `/wp-admin/plugins.php` 14 | 2. Click the **Add New Plugin** button. This will take you to the **Add New Plugins** page. 15 | 3. Click the **Upload Plugin** button. This will open a prompt with a file selector. 16 | 4. Using the file selector, select the ZIP file you downloaded, and then click **Install Now**. WordPress should automatically put the plugin files in place. 17 | - Move the files manually 18 | 1. Unzip the ZIP file you downloaded. 19 | 2. Copy the resulting directory into the plugins folder of your WordPress installation, usually found at `wp-content/plugins/`. 20 | 3. Activate the plugin by navigating to the **Plugins** page, finding **Hyperaudio Interactive Transcript**, and clicking the **Activate** link under the plugin name. 21 | 22 | ## Explainer videos 23 | 1. [How to use the Hyperaudio Wordpress Plugin – Part 1](https://youtu.be/3Qpq8kj4PxM) 24 | 2. [How to use the Hyperaudio Wordpress Plugin – Part 2](https://youtu.be/vIXHCYYSFM0) 25 | 3. [How to use the Hyperaudio Wordpress Plugin – Part 3](https://youtu.be/ly08N9S1ZlE) 26 | 27 | 28 | 29 | 4. [Web Monetization in the Hyperaudio Wordpress Plugin](https://youtu.be/8kRNh8iBkVk) 30 | 31 | --- 32 | (c) Copyright The Hyperaudio Project 33 | 34 | Thanks to [WFMT](https://www.wfmt.com)/[WTTW](https://www.wttw.com) and the [Studs Terkel Radio Archive](https://studsterkel.wfmt.com/) for sponsoring this project. 35 | 36 | Please consider donating via our [Patreon account](https://patreon.com/hyperaudio) 37 | -------------------------------------------------------------------------------- /admin/admin.php: -------------------------------------------------------------------------------- 1 | 37 |

Hyperaudio Interactive Transcript for Wordpress (v1.0.24) - How To

38 |

(Jump straight to the Transcript Maker)

39 | 40 | 41 | 173 | 174 | 175 |
176 | 177 |
178 | 179 |
180 |

NOTE: You can also transcribe, edit and create your hypertranscript using the Hyperaudio Lite Editor. To do this, export as HTML from the Hyperaudio Lite Editor and paste directly into your post between the Hyperaudio shortcode.

181 |
182 |

Pass the HTML transcript (created here) into the Hyperaudio shortcode and set the src attribute to reference the media you wish to associate it with.

183 |

For example:

184 |

[hyperaudio src="https://example.com/video/video.mp4"]
185 | <article>
186 | <section>
187 | <p>
188 | <span data-m="4470" data-d="0" class="speaker">Doc: </span>
189 | <span data-m="4470" data-d="270">We </span>
190 | <span data-m="4740" data-d="240">have </span>
191 | <span data-m="5010" data-d="300">two </span>
192 | <span data-m="5310" data-d="600">selves </span>
193 | ...
194 | </p>
195 | </section>
196 | </article>
197 | [/hyperaudio] 198 |
199 |

200 | 201 |

When defining the source of your media using the src attribute you will need to use embed versions of the URL for YouTube, Vimeo and SoundCloud.

202 |

For example:

203 |

https://www.youtube.com/embed/xLcsdc823dg

204 |

or

205 |

https://player.vimeo.com/video/749606407

206 |

or

207 |

https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/730479133&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true *

208 |

* Grab the snippet of code from the SoundCloud page containing the file you're interested in, clicking on Share and then Embed.

209 |

or

210 |

https://open.spotify.com/episode/4XAhcdJTXoffuDZglrEbSj

211 |

You can define various other attributes including:

212 |

213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 |
attributeexample valuefunction
width100%set the width of the transcript + media holder
height100%set the height of the media holder
transcript-height700pxset the height of the transcript itself
media-height640pxset the height of the audio or video
font-familyArial, Helvetica, sans-serif;set the font family of the transcript
idmytranscriptsets the id of the trancript for sharing purposes
show-activetruehighlights the word being played in a different colour. (false by default)
playerYouTubeAllows you to explicitly define type of player (SoundCloud, YouTube, Vimeo, Videojs, Spotify, NativeAudio)
webmonetizationtrueenables Web Monetization (false by default)
225 |

226 |

For example:

227 |

[hyperaudio src="https://example.com/video/video.mp4" width="90%" transcript-height="600px" webmonetization=true]
228 | <article>
229 | <section>
230 | <p>
231 | <span data-m="4470" data-d="0" class="speaker">Doc: </span>
232 | <span data-m="4470" data-d="270">We </span>
233 | <span data-m="4740" data-d="240">have </span>
234 | <span data-m="5010" data-d="300">two </span>
235 | <span data-m="5310" data-d="600">selves </span>
236 | ...
237 | </p>
238 | </section>
239 | </article>
240 | [/hyperaudio] 241 |
242 |

243 |

And for those with the caption generating version ...

244 |

245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 |
attributeexample valuefunction
captionsfalsegenerate captions (true by default)
caption-max32maximum set of characters in a caption line (37 by default)
caption-min19minimum set of characters in a caption line (21 by default)
languagefrsets the language of the captions
track-labelFrenchsets caption track label
253 |

254 |
255 | 256 |
257 | 258 |
259 |

Convert various formats into a Hypertranscript...

260 |

Paste your SRT (subtitle) file, Speechmatics JSON, Gentle JSON, Google STT JSON into the pane below and press the Convert! button.

261 | 262 |
263 | 264 | 265 |

266 | Input Format : 267 | 276 |

277 |

Take word-length into account when calculating word timings from SRT?

278 |
279 |
280 | 281 |
282 |

Paste here ⤵

283 |
284 | 285 |
286 | 287 |
288 | 289 | 290 | 291 |
292 |

hypertranscript appears here ⤵

293 | Markup View Rendered View 294 |
295 | 296 |
297 | 298 |

And format.

299 |
300 |

Paragraph split on delay:

301 |

0 10
302 | 2.0 seconds

303 |

Only split paras on text finishing with punctuation. (. ! ?)

304 |
305 |

306 |
307 | 308 |
309 | 310 | 311 | 312 |
313 | 314 | Download WebVTT ⬇ 315 | Download SRT ⬇ 316 |
317 | 318 |
319 | 320 |
321 | 322 | 324 |
325 | 326 | -------------------------------------------------------------------------------- /assets/native_audio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/native_audio.png -------------------------------------------------------------------------------- /assets/native_video.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/native_video.png -------------------------------------------------------------------------------- /assets/selecting_shortcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/selecting_shortcode.png -------------------------------------------------------------------------------- /assets/sharing_excerpt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/sharing_excerpt.png -------------------------------------------------------------------------------- /assets/shortcode_usage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/shortcode_usage.png -------------------------------------------------------------------------------- /assets/soundcloud_player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/soundcloud_player.png -------------------------------------------------------------------------------- /assets/transcript_converter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/transcript_converter.png -------------------------------------------------------------------------------- /assets/transcript_converter_howto.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/transcript_converter_howto.png -------------------------------------------------------------------------------- /assets/transcript_converter_howto_customize.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/transcript_converter_howto_customize.png -------------------------------------------------------------------------------- /assets/transcript_converter_interface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/transcript_converter_interface.png -------------------------------------------------------------------------------- /assets/transcript_converter_markup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/transcript_converter_markup.png -------------------------------------------------------------------------------- /assets/upload_media.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperaudio/wordpress-hyperaudio/62beb02ca0bbb60103a457899fc522656ccf67fb/assets/upload_media.png -------------------------------------------------------------------------------- /css/share-this.css: -------------------------------------------------------------------------------- 1 | .share-this-popover{max-width:8em;pointer-events:none;-webkit-filter:drop-shadow(0 1px 3px rgba(0,0,0,.35));filter:drop-shadow(0 1px 3px rgba(0,0,0,.35));-webkit-animation:a .3s;animation:a .3s}.share-this-popover:before{content:"";position:absolute;bottom:100%;left:50%;width:0;height:0;margin:.25em -.5em;border-width:.5em .5em 0;border-style:solid;border-color:#333 transparent}.share-this-popover>ul{pointer-events:auto;list-style:none;padding:0;margin:-.75em 0 0;white-space:nowrap;background:#333;color:#fff;border-radius:.25em;position:absolute;left:50%;-webkit-transform:translate(-50%,-100%);-ms-transform:translate(-50%,-100%);transform:translate(-50%,-100%)}.share-this-popover>ul>li{display:inline-block;width:2em;height:2em;line-height:2em;text-align:center}.share-this-popover>ul>li>a{display:inline-block;width:100%;height:100%;color:inherit;box-sizing:border-box;padding:.35em}.share-this-popover>ul>li>a:focus,.share-this-popover>ul>li>a>svg:hover{color:rgb(29,161,242)}.share-this-popover>ul>li>a>svg{vertical-align: inherit;}@media (pointer:coarse){.share-this-popover{font-size:150%}.share-this-popover:before{bottom:auto;top:100%;border-width:0 .5em .5em;margin-top:0}.share-this-popover>ul{top:100%;transform:translateX(-50%);margin:.5em 0 0}}@media (max-width:575px){.share-this-popover{left:0!important;right:0!important;width:auto!important;max-width:none}.share-this-popover:before{bottom:auto;top:100%;border-width:0 .5em .5em;margin-top:0}.share-this-popover>ul{top:100%;transform:translateX(-50%);margin:.5em 0 0;left:0;width:100%;transform:none;border-radius:0;text-align:center}}@-webkit-keyframes a{0%{-webkit-transform:translateY(-3em);opacity:0}80%{-webkit-transform:translateY(.5em);opacity:1}to{-webkit-transform:translateY(0)}}@keyframes a{0%{transform:translateY(-3em);opacity:0}80%{transform:translateY(.5em);opacity:1}to{transform:translateY(0)}} 2 | -------------------------------------------------------------------------------- /hyperaudio.php: -------------------------------------------------------------------------------- 1 | ", "", $transcript); 64 | 65 | global $globalid; 66 | $globalid++; 67 | $id = $globalid; 68 | 69 | if (is_null($transcriptid)) { 70 | $transcriptid = "hypertranscript".$id; 71 | } 72 | 73 | if (strtolower($player) == 'videojs') { 74 | $o .=''; 75 | } 76 | 77 | $o .=''; 209 | 210 | $o .=''; 216 | 217 | $o .='
'; 218 | 219 | if (strpos(strtolower($src), 'youtube.com') !== false || strpos(strtolower($src), 'youtu.be') !== false || strtolower($player) == 'youtube') { 220 | if (isset($atts['media-height'])) { 221 | $o .= '
'; 222 | } else { 223 | $o .= '
'; 224 | } 225 | } elseif (strpos(strtolower($src), 'vimeo.com') !== false || strtolower($player) == 'vimeo') { 226 | $o .= ''; 227 | } elseif (strpos(strtolower($src), 'soundcloud.com') !== false || strtolower($player) == 'soundcloud') { 228 | $o .= ''; 229 | } elseif (strtolower($player) == 'videojs') { 230 | $o .= '
'; 256 | 257 | $hyperaudioLink = ''; 258 | if ($showHyperaudioLink === true) { 259 | $hyperaudioLink = ''; 260 | } 261 | 262 | $o .='
'. wp_kses_post( $transcript ) . wp_kses_post( $hyperaudioLink ) . '
'; 263 | 264 | $o .= ' 278 | '; 279 | 280 | return $o; 281 | } 282 | 283 | function hyperaudio_init() 284 | { 285 | if (!is_admin()) { 286 | wp_enqueue_script('velocityjs', plugins_url('/js/velocity.js', __FILE__), [], '1.5.0'); 287 | wp_enqueue_script('hyperaudio_lite', plugins_url('/js/hyperaudio-lite.js', __FILE__), [], '2.3.1'); 288 | wp_enqueue_script('hyperaudio_caption', plugins_url('/js/caption.js', __FILE__), [], '2.1.4'); 289 | } 290 | } 291 | 292 | add_filter('plugin_action_links', 'hyperaudio_action_links', 10, 2); 293 | function hyperaudio_action_links($links, $file) 294 | { 295 | static $this_plugin; 296 | if (!$this_plugin) { 297 | $this_plugin = plugin_basename(__FILE__); 298 | } 299 | 300 | // check to make sure we are on the correct plugin 301 | if ($file == $this_plugin) { 302 | // the anchor tag and href to the URL we want. For a "Settings" link, this needs to be the url of your settings page 303 | $settings_link = 'Settings'; 304 | // add the link to the list 305 | array_unshift($links, $settings_link); 306 | } 307 | return $links; 308 | } 309 | 310 | if (is_admin()) { 311 | require('admin/admin.php'); 312 | } 313 | -------------------------------------------------------------------------------- /js/caption.js: -------------------------------------------------------------------------------- 1 | /*! (C) The Hyperaudio Project. MIT @license: en.wikipedia.org/wiki/MIT_License. */ 2 | /*! Version 2.1.4 */ 3 | 'use strict'; 4 | 5 | var caption = function () { 6 | var cap = {}; 7 | 8 | function formatSeconds(seconds) { 9 | if (typeof seconds == 'number') { 10 | //console.log("seconds = "+seconds); 11 | return new Date(seconds.toFixed(3) * 1000).toISOString().substring(11,23); 12 | } else { 13 | console.log('warning - attempting to format the non number: ' + seconds); 14 | return null; 15 | } 16 | } 17 | 18 | function convertTimecodeToSrt(timecode) { 19 | //the same as VTT format but milliseconds separated by a comma 20 | return timecode.substring(0,8) + "," + timecode.substring(9,12); 21 | } 22 | 23 | cap.init = function (transcriptId, playerId, maxLength, minLength, label, srclang) { 24 | var transcript = document.getElementById(transcriptId); 25 | var words = transcript.querySelectorAll('[data-m]'); 26 | var data = {}; 27 | data.segments = []; 28 | 29 | function segmentMeta(speaker, start, duration, chars) { 30 | this.speaker = speaker; 31 | this.start = start; 32 | this.duration = duration; 33 | this.chars = chars; 34 | this.words = []; 35 | } 36 | 37 | function wordMeta(start, duration, text) { 38 | this.start = start; 39 | this.duration = duration; 40 | this.text = text; 41 | } 42 | 43 | var thisWordMeta; 44 | var thisSegmentMeta = null; 45 | 46 | // defaults 47 | var maxLineLength = 37; 48 | var minLineLength = 21; 49 | var maxWordDuration = 2; //seconds 50 | 51 | var captionsVtt = 'WEBVTT\n'; 52 | var captionsSrt = ''; 53 | 54 | var endSentenceDelimiter = /[\.。?؟!]/g; 55 | var midSentenceDelimiter = /[,、–,،و:,…‥]/g; 56 | 57 | if (!isNaN(maxLength) && maxLength != null) { 58 | maxLineLength = maxLength; 59 | } 60 | 61 | if (!isNaN(minLength) && minLength != null) { 62 | minLineLength = minLength; 63 | } 64 | 65 | words.forEach(function (word, i) { 66 | if (thisSegmentMeta === null) { 67 | // create segment meta object 68 | thisSegmentMeta = new segmentMeta('', null, 0, 0, 0); 69 | } 70 | 71 | if (word.classList.contains('speaker')) { 72 | // checking that this is not a new segment AND a new empty segment wasn't already created 73 | if (thisSegmentMeta !== null && thisSegmentMeta.start !== null) { 74 | data.segments.push(thisSegmentMeta); // push the previous segment because it's a new speaker 75 | thisSegmentMeta = new segmentMeta('', null, 0, 0, 0); 76 | } 77 | 78 | thisSegmentMeta.speaker = word.innerText; 79 | } else { 80 | var thisStart = parseInt(word.getAttribute('data-m')) / 1000; 81 | var thisDuration = parseInt(word.getAttribute('data-d')) / 1000; 82 | 83 | if (isNaN(thisStart)) { 84 | thisStart = 0; 85 | } 86 | 87 | // data-d (duration) is an optional attribute, if it doesn't exist 88 | // use the start time of the next word (if it exists) or for the last word 89 | // pick a sensible duration. 90 | 91 | if (isNaN(thisDuration)) { 92 | if (i < (words.length - 1)) { 93 | thisDuration = (parseInt(words[i+1].getAttribute('data-m') - 1) / 1000) - thisStart; 94 | if (thisDuration > maxWordDuration) { 95 | thisDuration = maxWordDuration; 96 | } 97 | } else { 98 | thisDuration = 5; // sensible default for the last word 99 | } 100 | } 101 | 102 | var thisText = word.innerText; 103 | 104 | thisWordMeta = new wordMeta(thisStart, thisDuration, thisText); 105 | 106 | if (thisSegmentMeta.start === null) { 107 | thisSegmentMeta.start = thisStart; 108 | thisSegmentMeta.duration = 0; 109 | thisSegmentMeta.chars = 0; 110 | } 111 | 112 | thisSegmentMeta.duration += thisDuration; 113 | thisSegmentMeta.chars += thisText.length; 114 | 115 | thisSegmentMeta.words.push(thisWordMeta); 116 | 117 | // remove spaces first just in case 118 | var lastChar = thisText.replace(/\s/g, '').slice(-1); 119 | if (lastChar.match(endSentenceDelimiter)) { 120 | data.segments.push(thisSegmentMeta); 121 | thisSegmentMeta = null; 122 | } 123 | } 124 | }); 125 | 126 | function captionMeta(start, stop, text) { 127 | this.start = start; 128 | this.stop = stop; 129 | this.text = text; 130 | } 131 | 132 | var captions = []; 133 | var thisCaption = null; 134 | 135 | data.segments.map(function (segment, i, arr) { 136 | // If the entire segment fits on a line, add it to the captions. 137 | if (segment.chars < maxLineLength) { 138 | 139 | if (segment.duration === 0){ 140 | if (i < arr.length) { 141 | segment.duration = arr[i+1].start - segment.start; 142 | } else { 143 | segment.duration = 5 * 1000; 144 | } 145 | } 146 | 147 | thisCaption = new captionMeta( 148 | formatSeconds(segment.start), 149 | formatSeconds(segment.start + segment.duration), 150 | '', 151 | ); 152 | 153 | segment.words.forEach(function (wordMeta) { 154 | thisCaption.text += wordMeta.text; 155 | }); 156 | 157 | thisCaption.text += '\n'; 158 | //console.log("0. pushing because the whole segment fits on a line!"); 159 | //console.log(thisCaption); 160 | captions.push(thisCaption); 161 | thisCaption = null; 162 | } else { 163 | // The number of chars in this segment is longer than our single line maximum 164 | 165 | var charCount = 0; 166 | var lineText = ''; 167 | var firstLine = true; 168 | var lastOutTime; 169 | var lastInTime = null; 170 | 171 | segment.words.forEach(function (wordMeta, index) { 172 | var lastChar = wordMeta.text.replace(/\s/g, '').slice(-1); 173 | 174 | if (lastInTime === null) { 175 | // if it doesn't exist yet set the caption start time to the word's start time. 176 | lastInTime = wordMeta.start; 177 | } 178 | 179 | // Are we over the minimum length of a line and hitting a good place to split mid-sentence? 180 | if (charCount + wordMeta.text.length > minLineLength && lastChar.match(midSentenceDelimiter)) { 181 | if (firstLine === true) { 182 | thisCaption = new captionMeta( 183 | formatSeconds(lastInTime), 184 | formatSeconds(wordMeta.start + wordMeta.duration), 185 | '', 186 | ); 187 | thisCaption.text += lineText + wordMeta.text + '\n'; 188 | 189 | //check for last word in segment, if it is we can push a one line caption, if not – move on to second line 190 | 191 | if (index + 1 >= segment.words.length) { 192 | //console.log("1. pushing because we're at a good place to split, we're on the first line but it's the last word of the segment."); 193 | //console.log(thisCaption); 194 | captions.push(thisCaption); 195 | thisCaption = null; 196 | } else { 197 | firstLine = false; 198 | } 199 | } else { 200 | // We're on the second line ... we're over the minimum chars and in a good place to split – let's push the caption 201 | 202 | thisCaption.stop = formatSeconds(wordMeta.start + wordMeta.duration); 203 | thisCaption.text += lineText + wordMeta.text; 204 | //console.log("2. pushing because we're on the second line and have a good place to split"); 205 | //console.log(thisCaption); 206 | captions.push(thisCaption); 207 | thisCaption = null; 208 | firstLine = true; 209 | } 210 | 211 | // whether first line or not we should reset ready for a new caption 212 | charCount = 0; 213 | lineText = ''; 214 | lastInTime = null; 215 | } else { 216 | // we're not over the minimum length with a suitable splitting point 217 | 218 | // If we add this word are we over the maximum? 219 | if (charCount + wordMeta.text.length > maxLineLength) { 220 | if (firstLine === true) { 221 | if (lastOutTime === undefined) { 222 | lastOutTime = wordMeta.start + wordMeta.duration; 223 | } 224 | 225 | thisCaption = new captionMeta(formatSeconds(lastInTime), formatSeconds(lastOutTime), ''); 226 | thisCaption.text += lineText + '\n'; 227 | 228 | // It's just the first line so we should only push a new caption if it's the very last word! 229 | 230 | if (index >= segment.words.length) { 231 | captions.push(thisCaption); 232 | thisCaption = null; 233 | } else { 234 | firstLine = false; 235 | } 236 | } else { 237 | // We're on the second line and since we're over the maximum with the next word we should push this caption! 238 | 239 | thisCaption.stop = formatSeconds(lastOutTime); 240 | thisCaption.text += lineText; 241 | 242 | captions.push(thisCaption); 243 | 244 | thisCaption = null; 245 | firstLine = true; 246 | } 247 | 248 | // do the stuff we need to do to start a new line 249 | charCount = wordMeta.text.length; 250 | lineText = wordMeta.text; 251 | lastInTime = wordMeta.start; 252 | } else { 253 | // We're not over the maximum with this word, update the line length and add the word to the text 254 | 255 | charCount += wordMeta.text.length; 256 | lineText += wordMeta.text; 257 | } 258 | } 259 | 260 | // for every word update the lastOutTime 261 | lastOutTime = wordMeta.start + wordMeta.duration; 262 | }); 263 | 264 | // we're out of words for this segment - decision time! 265 | if (thisCaption !== null) { 266 | // The caption had been started, time to add whatever text we have and add a stop point 267 | thisCaption.stop = formatSeconds(lastOutTime); 268 | thisCaption.text += lineText; 269 | //console.log("3. pushing at end of segment when new caption HAS BEEN created"); 270 | //console.log(thisCaption); 271 | captions.push(thisCaption); 272 | thisCaption = null; 273 | } else { 274 | // caption hadn't been started yet - create one! 275 | if (lastInTime !== null) { 276 | thisCaption = new captionMeta(formatSeconds(lastInTime), formatSeconds(lastOutTime), lineText); 277 | //console.log("4. pushing at end of segment when new caption has yet to be created"); 278 | //console.log(thisCaption); 279 | captions.push(thisCaption); 280 | thisCaption = null; 281 | } 282 | } 283 | } 284 | }); 285 | 286 | captions.forEach(function (caption, i) { 287 | captionsVtt += '\n' + caption.start + ' --> ' + caption.stop + '\n' + caption.text + '\n'; 288 | //console.log(caption.start + ' --> ' + caption.stop + '\n' + caption.text); 289 | captionsSrt += '\n' + (i + 1) + '\n' + convertTimecodeToSrt(caption.start) + ' --> ' + convertTimecodeToSrt(caption.stop) + '\n' + caption.text + '\n'; 290 | }); 291 | 292 | var video = document.getElementById(playerId); 293 | 294 | if (video !== null) { 295 | video.addEventListener("loadedmetadata", function listener() { 296 | 297 | var track = document.getElementById(playerId+'-vtt'); 298 | 299 | if (track !== null){ 300 | track.kind = "captions"; 301 | 302 | if (label !== undefined) { 303 | //console.log("setting label as "+label); 304 | track.label = label; 305 | } 306 | 307 | if (srclang !== undefined) { 308 | //console.log("setting srclang as "+srclang); 309 | track.srclang = srclang; 310 | } 311 | 312 | track.src = "data:text/vtt,"+encodeURIComponent(captionsVtt); 313 | video.textTracks[0].mode = "showing"; 314 | video.removeEventListener("loadedmetadata", listener, true); 315 | } 316 | 317 | }, true); 318 | 319 | if (video.textTracks !== undefined && video.textTracks[0] !== undefined) { 320 | video.textTracks[0].mode = "showing"; 321 | } 322 | } 323 | 324 | function captionsObj(vtt, srt, data) { 325 | // clean up – remove any double blank lines 326 | // and blank line at the start of srt 327 | 328 | if (srt.charAt(0) !== "1") { 329 | srt = srt.slice(1); 330 | } 331 | 332 | this.vtt = vtt.replaceAll("\n\n\n","\n\n"); 333 | this.srt = srt.replaceAll("\n\n\n","\n\n"); 334 | this.data = captions; 335 | } 336 | 337 | return new captionsObj(captionsVtt, captionsSrt, captions); 338 | }; 339 | 340 | return cap; 341 | }; -------------------------------------------------------------------------------- /js/converter.js: -------------------------------------------------------------------------------- 1 | var $ = jQuery; // needed for wordpress 2 | 3 | $(document).ready(function() { 4 | var p = document.getElementById('para-split'); 5 | var cp = document.getElementById('current-para-split'); 6 | var paraSplitTime = p.value; 7 | var paraPunct = $('#para-punctuation').prop('checked'); 8 | 9 | p.addEventListener( 10 | 'input', 11 | function() { 12 | cp.innerHTML = p.value; 13 | paraSplitTime = p.value; 14 | }, 15 | false 16 | ); 17 | 18 | $('#para-punctuation').change(function() { 19 | if (this.checked) { 20 | paraPunct = $('#para-punctuation').prop('checked'); 21 | } 22 | }); 23 | 24 | $('#markup-view').click(function() { 25 | $('#rendered-view').addClass('inactive'); 26 | $(this).removeClass('inactive'); 27 | $('#rtranscript').hide(); 28 | 29 | var regex = /\span>(.*?)\ 0) { 35 | strToMatch = strToMatch.replace(""+matches[1], matches[1]+""); 36 | } 37 | } 38 | 39 | $('#htranscript').val(strToMatch); 40 | $('#htranscript').show(); 41 | return false; 42 | }); 43 | 44 | $('#rendered-view').click(function() { 45 | $('#markup-view').addClass('inactive'); 46 | $(this).removeClass('inactive'); 47 | $('#htranscript').hide(); 48 | $('#rtranscript').html("rendering..."); 49 | $('#rtranscript').show(); 50 | 51 | setTimeout(renderTranscript, 100); 52 | 53 | return false; 54 | }); 55 | 56 | function renderTranscript() { 57 | $('#rtranscript').html($('#htranscript').val()); 58 | 59 | //document.getElementById("gen-subs").addEventListener("click", genSubs); 60 | $('#gen-subs').click(genSubs); 61 | //document.getElementById("generate-captions").style.display = 'inline'; 62 | $('#generate-captions').show(); 63 | 64 | function genSubs(){ 65 | var cap1 = caption(); 66 | var subs = cap1.init("rtranscript", null, null, null); 67 | //console.log(subs.vtt); 68 | //console.log(subs.srt); 69 | //var downloadLinkVtt = document.getElementById("download-vtt"); 70 | //downloadLinkVtt.setAttribute("href", 'data:text/vtt,'+encodeURIComponent(subs.vtt)); 71 | //downloadLinkVtt.style.display = 'inline'; 72 | $('#download-vtt').attr("href", 'data:text/vtt,'+encodeURIComponent(subs.vtt)).show(); 73 | 74 | //var downloadLinkSrt = document.getElementById("download-srt"); 75 | //downloadLinkSrt.setAttribute("href", 'data:text/vtt,'+encodeURIComponent(subs.srt)); 76 | //downloadLinkSrt.style.display = 'inline'; 77 | $('#download-srt').attr("href", 'data:text/vtt,'+encodeURIComponent(subs.srt)).show(); 78 | }; 79 | } 80 | 81 | String.prototype.replaceAll = function(search, replacement) { 82 | var target = this; 83 | return target.replace(new RegExp(search, 'g'), replacement); 84 | }; 85 | 86 | // From popcorn.parserSRT.js 87 | 88 | function parseSRT(data) { 89 | 90 | var i = 0, 91 | len = 0, 92 | idx = 0, 93 | lines, 94 | time, 95 | text, 96 | sub; 97 | 98 | // Simple function to convert HH:MM:SS,MMM or HH:MM:SS.MMM to SS.MMM 99 | // Assume valid, returns 0 on error 100 | 101 | var toSeconds = function(t_in) { 102 | var t = t_in.split(':'); 103 | 104 | try { 105 | var s = t[2].split(','); 106 | 107 | // Just in case a . is decimal seperator 108 | if (s.length === 1) { 109 | s = t[2].split('.'); 110 | } 111 | 112 | return ( 113 | parseFloat(t[0], 10) * 3600 + 114 | parseFloat(t[1], 10) * 60 + 115 | parseFloat(s[0], 10) + 116 | parseFloat(s[1], 10) / 1000 117 | ); 118 | } catch (e) { 119 | return 0; 120 | } 121 | }; 122 | 123 | var outputString = '

'; 124 | var lineBreaks = $('#line-breaks').prop('checked'); 125 | var ltime = 0; 126 | var ltext; 127 | 128 | // Here is where the magic happens 129 | // Split on line breaks 130 | lines = data.split(/(?:\r\n|\r|\n)/gm); 131 | len = lines.length; 132 | 133 | for (i = 0; i < len; i++) { 134 | sub = {}; 135 | text = []; 136 | 137 | sub.id = parseInt(lines[i++], 10); 138 | 139 | // Split on '-->' delimiter, trimming spaces as well 140 | 141 | try { 142 | time = lines[i++].split(/[\t ]*-->[\t ]*/); 143 | } catch (e) { 144 | alert('Warning. Possible issue on line ' + i + ": '" + lines[i] + "'."); 145 | break; 146 | } 147 | 148 | sub.start = toSeconds(time[0]); 149 | 150 | // So as to trim positioning information from end 151 | if (!time[1]) { 152 | alert('Warning. Issue on line ' + i + ": '" + lines[i] + "'."); 153 | return; 154 | } 155 | 156 | idx = time[1].indexOf(' '); 157 | if (idx !== -1) { 158 | time[1] = time[1].substr(0, idx); 159 | } 160 | sub.end = toSeconds(time[1]); 161 | 162 | // Build single line of text from multi-line subtitle in file 163 | while (i < len && lines[i]) { 164 | text.push(lines[i++]); 165 | } 166 | 167 | // Join into 1 line, SSA-style linebreaks 168 | // Strip out other SSA-style tags 169 | sub.text = text.join('\\N').replace(/\{(\\[\w]+\(?([\w\d]+,?)+\)?)+\}/gi, ''); 170 | 171 | // Escape HTML entities 172 | sub.text = sub.text.replace(//g, '>'); 173 | 174 | // Unescape great than and less than when it makes a valid html tag of a supported style (font, b, u, s, i) 175 | // Modified version of regex from Phil Haack's blog: http://haacked.com/archive/2004/10/25/usingregularexpressionstomatchhtml.aspx 176 | // Later modified by kev: http://kevin.deldycke.com/2007/03/ultimate-regular-expression-for-html-tag-parsing-with-php/ 177 | sub.text = sub.text.replace( 178 | /<(\/?(font|b|u|i|s))((\s+(\w|\w[\w\-]*\w)(\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)+\s*|\s*)(\/?)>/gi, 179 | '<$1$3$7>' 180 | ); 181 | //sub.text = sub.text.replace( /\\N/gi, "
" ); 182 | sub.text = sub.text.replace(/\\N/gi, ' '); 183 | 184 | var splitMode = 0; 185 | 186 | var wordLengthSplit = $('#word-length').prop('checked'); 187 | 188 | // enhancements to take account of word length 189 | 190 | var swords = sub.text.split(' '); 191 | var sduration = sub.end - sub.start; 192 | var stimeStep = sduration / swords.length; 193 | 194 | // determine length of words 195 | 196 | var swordLengths = []; 197 | var swordTimes = []; 198 | 199 | var totalLetters = 0; 200 | for (var si = 0, sl = swords.length; si < sl; ++si) { 201 | totalLetters = totalLetters + swords[si].length; 202 | swordLengths[si] = swords[si].length; 203 | } 204 | 205 | var letterTime = sduration / totalLetters; 206 | var wordStart = 0; 207 | 208 | for (var si = 0, sl = swords.length; si < sl; ++si) { 209 | var wordTime = swordLengths[si] * letterTime; 210 | var stime; 211 | if (wordLengthSplit) { 212 | stime = Math.round((sub.start + si * stimeStep) * 1000); 213 | } else { 214 | stime = Math.round((wordStart + sub.start) * 1000); 215 | } 216 | 217 | wordStart = wordStart + wordTime; 218 | var stext = swords[si]; 219 | 220 | if (stime - ltime > paraSplitTime * 1000 && paraSplitTime > 0) { 221 | 222 | var punctPresent = 223 | ltext && (ltext.indexOf('.') > 0 || ltext.indexOf('?') > 0 || ltext.indexOf('!') > 0); 224 | if (!paraPunct || (paraPunct && punctPresent)) { 225 | outputString += '

'; 226 | } 227 | } 228 | 229 | outputString += '' + stext + ' '; 230 | 231 | ltime = stime; 232 | ltext = stext; 233 | 234 | if (lineBreaks) outputString = outputString + '\n'; 235 | } 236 | } 237 | return outputString + '

'; 238 | } 239 | 240 | $('#transform').click(function() { 241 | $('#transform-spinner').show(); 242 | $('#htranscript').val("converting..."); 243 | setTimeout(generateTranscript, 100); 244 | }); 245 | 246 | function generateTranscript() { 247 | 248 | var input = $('#subtitles').val(); 249 | 250 | var ht; 251 | 252 | var format = $('#format-select').val(); 253 | 254 | switch (format) { 255 | 256 | case 'oe': 257 | var data = JSON.parse(input); 258 | var items = ['
\n

']; 259 | $.each(data.content.paragraphs, function(key, val) { 260 | var paraStart = Math.round(val.start*1000); 261 | items.push( 262 | '\n' + 264 | val.speaker + 265 | ' ' 266 | ); 267 | 268 | var lastStart = 0; 269 | 270 | $.each(val.words, function(k, v) { 271 | if (typeof v.start !== 'undefined') { 272 | items.push( 273 | '\n' + 275 | v.text + 276 | ' ' 277 | ); 278 | lastStart = v.start; 279 | } else { 280 | 281 | if (k === 0) { 282 | lastStart = paraStart; 283 | } 284 | 285 | items.push( 286 | '\n' + 288 | v.text + 289 | ' ' 290 | ); 291 | } 292 | }); 293 | items.push('

'); 294 | }); 295 | 296 | items.push('

'); 297 | 298 | ht = items.join(''); 299 | 300 | // remove empty paras 301 | 302 | ht = ht.split("

").join(""); 303 | 304 | break; 305 | 306 | case 'google': 307 | var data = JSON.parse(input); 308 | 309 | var items = ['

']; 310 | 311 | $.each(data.response.results, function(key, val) { 312 | $.each(val.alternatives, function(k, v) { 313 | for (var i = 0; i < v.words.length; i++) { 314 | items.push( 315 | '' + 320 | v.words[i].word + 321 | ' ' 322 | ); 323 | 324 | 325 | if (i > 0 && Math.round(parseFloat(v.words[i].startTime)) - Math.round(parseFloat(v.words[i-1].startTime)) > paraSplitTime && paraSplitTime > 0) { 326 | items.push('

'); 327 | } 328 | } 329 | }); 330 | }); 331 | 332 | items.push('

'); 333 | 334 | ht = items.join(''); 335 | break; 336 | 337 | case 'speechmatics': 338 | var data = JSON.parse(input); 339 | var items = ['

']; 340 | $.each(data, function(key, val) { 341 | if (key == 'words') { 342 | for (var i = 0; i < val.length; i++) { 343 | var punct = ""; 344 | if ((i+1) < val.length && val[i+1].name === ".") { 345 | punct = "."; 346 | } 347 | 348 | if (val[i].name !== ".") { 349 | items.push( 350 | '' + 357 | val[i].name + punct + 358 | ' ' 359 | ); 360 | } 361 | 362 | if (i > 0 && Math.round(parseFloat(val[i].time)) - Math.round(parseFloat(val[i-1].time)) > paraSplitTime && paraSplitTime > 0) { 363 | if ((paraPunct && punct === ".") || (paraPunct === false)) { 364 | items.push('

'); 365 | } 366 | } 367 | } 368 | } 369 | }); 370 | 371 | items.push('

'); 372 | 373 | ht = items.join(''); 374 | break; 375 | 376 | case 'dpe': 377 | var data = JSON.parse(input); 378 | 379 | var words = data.words; 380 | var paras = data.paragraphs; 381 | var items = ['
']; 382 | 383 | $.each(words, function(i, word) { 384 | 385 | $.each(paras, function(j, para) { 386 | if (word.start === para.start) { 387 | items.push("

"); 388 | 389 | if (para.speaker.length > 0){ 390 | items.push('['+para.speaker+'] '); 391 | } 392 | } 393 | }); 394 | 395 | items.push( 396 | '' + 401 | word.text + " " + 402 | ' ' 403 | ); 404 | 405 | $.each(paras, function(j, para) { 406 | if (word.end === para.end) { 407 | items.push("

"); 408 | } 409 | }); 410 | }); 411 | 412 | items.push('

'); 413 | 414 | ht = items.join(''); 415 | break; 416 | 417 | case 'gentle': 418 | var data = JSON.parse(input); 419 | 420 | wds = data['words'] || []; 421 | transcript = data['transcript']; 422 | 423 | var trans = document.createElement('p'); 424 | 425 | trans.innerHTML = ''; 426 | 427 | var currentOffset = 0; 428 | var wordCounter = 0; 429 | var lastOutTime = 0; 430 | 431 | wds.forEach(function(wd) { 432 | var newlineDetected = false; 433 | 434 | if (wd.startOffset > currentOffset) { 435 | var txt = transcript.slice(currentOffset, wd.startOffset); 436 | newlineDetected = /\r|\n/.exec(txt); 437 | 438 | if (trans.lastChild) { 439 | trans.lastChild.text += txt + " "; 440 | } else { 441 | // this happens only at the beginning when offset not zero 442 | var span = document.createElement('span'); 443 | var initialWd = document.createTextNode(txt + " "); 444 | var initialDatam = document.createAttribute('data-m'); 445 | var initialDatad = document.createAttribute('data-d'); 446 | 447 | span.appendChild(initialWd); 448 | initialDatam.value = 0; 449 | initialDatad.value = 0; 450 | span.setAttributeNode(initialDatam); 451 | span.setAttributeNode(initialDatad); 452 | trans.appendChild(span); 453 | trans.appendChild(span); 454 | } 455 | 456 | if (newlineDetected) { 457 | var lineBreak = document.createElement('br'); 458 | trans.appendChild(lineBreak); 459 | } 460 | currentOffset = wd.startOffset; 461 | } 462 | 463 | var datam = document.createAttribute('data-m'); 464 | var datad = document.createAttribute('data-d'); 465 | 466 | var word = document.createElement('span'); 467 | 468 | var startOffset = wd.startOffset; 469 | var endOffset = wd.endOffset + 1; 470 | 471 | var txt = transcript.slice(startOffset, endOffset); 472 | 473 | // Check to see if previous letter is a character 474 | // AND the one before it a space, 475 | // if so include it. 476 | 477 | var previousChar = transcript[startOffset-1]; 478 | 479 | if (wordCounter > 0 && previousChar !== ' ' && transcript[startOffset-2] === ' ') { 480 | txt = previousChar + txt; 481 | } 482 | 483 | // Look ahead to see if next word's previous letter is a space ... 484 | // if it's a character we don't want to add a space to THIS word, 485 | // UNLESS the character before that is a space 486 | // because (for example) it might be a start of a hyphenated word. 487 | 488 | if (wordCounter + 1 < wds.length) { 489 | var nextWordCharBeforeStartIndex = wds[wordCounter + 1].startOffset - 1; 490 | if (transcript[nextWordCharBeforeStartIndex] === ' ' || transcript[nextWordCharBeforeStartIndex-1] === ' ') { 491 | if (!txt.endsWith(" ")){ 492 | txt = txt + " "; 493 | } 494 | } 495 | } 496 | 497 | if(txt.startsWith(' ')){ //trim leading space 498 | txt = txt.substring(1); 499 | } 500 | 501 | var wordText = document.createTextNode(txt); 502 | word.appendChild(wordText); 503 | 504 | if (wd.start !== undefined) { 505 | datam.value = Math.floor(wd.start * 1000); 506 | datad.value = Math.floor((wd.end - wd.start) * 1000); 507 | } else { 508 | // look ahead to the next timed word 509 | for (var i = wordCounter; i < wds.length - 1; i++) { 510 | if (wds[i + 1].start !== undefined) { 511 | datam.value = Math.floor(wds[i + 1].start * 1000); 512 | break; 513 | } 514 | } 515 | datad.value = '100'; // default duration when not known 516 | } 517 | 518 | if (datam.value < lastOutTime) { 519 | datam.value = lastOutTime + 1; 520 | } 521 | 522 | word.setAttributeNode(datam); 523 | word.setAttributeNode(datad); 524 | 525 | lastOutTime = parseInt(datam.value) + parseInt(datad.value); 526 | 527 | trans.appendChild(word); 528 | 529 | currentOffset = wd.endOffset; 530 | wordCounter++; 531 | }); 532 | 533 | currentOffset = transcript.length; 534 | 535 | article = document.createElement('article'); 536 | section = document.createElement('section'); 537 | 538 | section.appendChild(trans); 539 | article.appendChild(section); 540 | 541 | ht = article.outerHTML; 542 | 543 | //newlines can cause issues within HTML tags 544 | ht = ht.replace(/(?:\r\n|\r|\n)/g, ''); 545 | 546 | ht = ht.replace(new RegExp('
', 'g'), '

'); 547 | 548 | // replace all unneeded empty paras 549 | ht = ht.replace(new RegExp('

', 'g'), ''); 550 | 551 | break; 552 | 553 | case 'srt': 554 | ht = parseSRT(input); 555 | break; 556 | 557 | case 'other': 558 | var xmlString = input, 559 | parser = new DOMParser(), 560 | doc = parser.parseFromString(xmlString, 'text/xml'); 561 | 562 | var transcript = doc.getElementsByTagName('section')[0]; 563 | 564 | for (var i = 0; i < doc.getElementsByClassName('speaker').length; i++) { 565 | transcript.getElementsByClassName('speaker')[i].innerHTML = 566 | '[' + 567 | transcript.getElementsByClassName('speaker')[i].innerHTML.replace(': ', '') + 568 | '] '; 569 | var datam = document.createAttribute('data-m'); 570 | var datad = document.createAttribute('data-d'); 571 | datam.value = transcript 572 | .getElementsByClassName('speaker') 573 | [i].nextElementSibling.getAttribute('data-m'); 574 | datad.value = '1'; 575 | transcript.getElementsByClassName('speaker')[i].setAttributeNode(datam); 576 | transcript.getElementsByClassName('speaker')[i].setAttributeNode(datad); 577 | } 578 | 579 | var transcriptText = transcript.outerHTML; 580 | 581 | ht = '
' + transcriptText + '
'; 582 | } 583 | 584 | $('#htranscript').val(ht); 585 | $('#rtranscript').html(ht); 586 | 587 | $('#transform-spinner').hide(); 588 | return false; 589 | } 590 | }); -------------------------------------------------------------------------------- /js/hyperaudio-lite.js: -------------------------------------------------------------------------------- 1 | /*! (C) The Hyperaudio Project. MIT @license: en.wikipedia.org/wiki/MIT_License. */ 2 | /*! Version 2.3.1 */ 3 | 4 | 'use strict'; 5 | 6 | // Base player class to handle common player functionality 7 | class BasePlayer { 8 | constructor(instance) { 9 | this.player = this.initPlayer(instance); // Initialize the player 10 | this.paused = true; // Set initial paused state 11 | if (this.player) { 12 | this.attachEventListeners(instance); // Attach event listeners for play and pause 13 | } 14 | } 15 | 16 | // Method to initialize the player - to be implemented by subclasses 17 | initPlayer(instance) { 18 | throw new Error('initPlayer method should be implemented by subclasses'); 19 | } 20 | 21 | // Method to attach common event listeners 22 | attachEventListeners(instance) { 23 | this.player.addEventListener('pause', instance.pausePlayHead.bind(instance), false); 24 | this.player.addEventListener('play', instance.preparePlayHead.bind(instance), false); 25 | } 26 | 27 | // Method to get the current time of the player 28 | getTime() { 29 | return Promise.resolve(this.player.currentTime); 30 | } 31 | 32 | // Method to set the current time of the player 33 | setTime(seconds) { 34 | this.player.currentTime = seconds; 35 | } 36 | 37 | // Method to play the media 38 | play() { 39 | this.player.play(); 40 | this.paused = false; 41 | } 42 | 43 | // Method to pause the media 44 | pause() { 45 | this.player.pause(); 46 | this.paused = true; 47 | } 48 | } 49 | 50 | // Class for native HTML5 player 51 | class NativePlayer extends BasePlayer { 52 | // Initialize the native HTML5 player 53 | initPlayer(instance) { 54 | return instance.player; 55 | } 56 | } 57 | 58 | // Class for SoundCloud player 59 | class SoundCloudPlayer extends BasePlayer { 60 | // Initialize the SoundCloud player 61 | initPlayer(instance) { 62 | return SC.Widget(instance.player.id); 63 | } 64 | 65 | // Attach event listeners specific to SoundCloud player 66 | attachEventListeners(instance) { 67 | this.player.bind(SC.Widget.Events.PAUSE, instance.pausePlayHead.bind(instance)); 68 | this.player.bind(SC.Widget.Events.PLAY, instance.preparePlayHead.bind(instance)); 69 | } 70 | 71 | // Get the current time of the SoundCloud player 72 | getTime() { 73 | return new Promise(resolve => { 74 | this.player.getPosition(ms => resolve(ms / 1000)); 75 | }); 76 | } 77 | 78 | // Set the current time of the SoundCloud player 79 | setTime(seconds) { 80 | this.player.seekTo(seconds * 1000); 81 | } 82 | } 83 | 84 | // Class for VideoJS player 85 | class VideoJSPlayer extends BasePlayer { 86 | // Initialize the VideoJS player 87 | initPlayer(instance) { 88 | return videojs.getPlayer(instance.player.id); 89 | } 90 | 91 | // Get the current time of the VideoJS player 92 | getTime() { 93 | return Promise.resolve(this.player.currentTime()); 94 | } 95 | 96 | // Set the current time of the VideoJS player 97 | setTime(seconds) { 98 | this.player.currentTime(seconds); 99 | } 100 | } 101 | 102 | // Class for Vimeo player 103 | class VimeoPlayer extends BasePlayer { 104 | // Initialize the Vimeo player 105 | initPlayer(instance) { 106 | const iframe = document.querySelector('iframe'); 107 | return new Vimeo.Player(iframe); 108 | } 109 | 110 | // Attach event listeners specific to Vimeo player 111 | attachEventListeners(instance) { 112 | this.player.ready().then(instance.checkPlayHead.bind(instance)); 113 | this.player.on('play', instance.preparePlayHead.bind(instance)); 114 | this.player.on('pause', instance.pausePlayHead.bind(instance)); 115 | } 116 | 117 | // Get the current time of the Vimeo player 118 | getTime() { 119 | return this.player.getCurrentTime(); 120 | } 121 | 122 | // Set the current time of the Vimeo player 123 | setTime(seconds) { 124 | this.player.setCurrentTime(seconds); 125 | } 126 | } 127 | 128 | // Class for YouTube player 129 | class YouTubePlayer extends BasePlayer { 130 | // Initialize the YouTube player by loading YouTube IFrame API 131 | initPlayer(instance) { 132 | // Defer attaching event listeners until the player is ready 133 | this.isReady = false; 134 | 135 | // Load the YouTube IFrame API script 136 | if (!document.getElementById('iframe-demo')) { 137 | const tag = document.createElement('script'); 138 | tag.id = 'iframe-demo'; 139 | tag.src = 'https://www.youtube.com/iframe_api'; 140 | const firstScriptTag = document.getElementsByTagName('script')[0]; 141 | firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 142 | } 143 | 144 | // Set the global callback for the YouTube IFrame API 145 | window.onYouTubeIframeAPIReady = this.onYouTubeIframeAPIReady.bind(this, instance); 146 | } 147 | 148 | // Callback when YouTube IFrame API is ready 149 | onYouTubeIframeAPIReady(instance) { 150 | this.player = new YT.Player(instance.player.id, { 151 | events: { 152 | onStateChange: this.onPlayerStateChange.bind(this, instance), 153 | onReady: this.onPlayerReady.bind(this) 154 | } 155 | }); 156 | } 157 | 158 | // Event handler when the YouTube player is ready 159 | onPlayerReady() { 160 | this.isReady = true; 161 | } 162 | 163 | // Handle YouTube player state changes (play, pause) 164 | onPlayerStateChange(instance, event) { 165 | if (event.data === YT.PlayerState.PLAYING) { // Playing 166 | instance.preparePlayHead(); 167 | this.paused = false; 168 | } else if (event.data === YT.PlayerState.PAUSED) { // Paused 169 | instance.pausePlayHead(); 170 | this.paused = true; 171 | } 172 | } 173 | 174 | // Get the current time of the YouTube player 175 | getTime() { 176 | if (this.isReady) { 177 | return Promise.resolve(this.player.getCurrentTime()); 178 | } else { 179 | return Promise.resolve(0); // Return 0 if the player is not ready 180 | } 181 | } 182 | 183 | // Set the current time of the YouTube player 184 | setTime(seconds) { 185 | if (this.isReady) { 186 | this.player.seekTo(seconds, true); 187 | } 188 | } 189 | 190 | // Play the YouTube video 191 | play() { 192 | if (this.isReady) { 193 | this.player.playVideo(); 194 | } 195 | } 196 | 197 | // Pause the YouTube video 198 | pause() { 199 | if (this.isReady) { 200 | this.player.pauseVideo(); 201 | } 202 | } 203 | } 204 | 205 | // Class for Spotify player 206 | class SpotifyPlayer extends BasePlayer { 207 | // Initialize the Spotify player by setting up the Spotify IFrame API 208 | initPlayer(instance) { 209 | window.onSpotifyIframeApiReady = IFrameAPI => { 210 | const element = document.getElementById(instance.player.id); 211 | const srcValue = element.getAttribute('src'); 212 | const episodeID = this.extractEpisodeID(srcValue); 213 | 214 | const options = { uri: `spotify:episode:${episodeID}` }; 215 | const callback = player => { 216 | this.player = player; 217 | player.addListener('playback_update', e => { 218 | if (e.data.isPaused !== true) { 219 | this.currentTime = e.data.position / 1000; 220 | instance.preparePlayHead(); 221 | this.paused = false; 222 | } else { 223 | instance.pausePlayHead(); 224 | this.paused = true; 225 | } 226 | }); 227 | 228 | player.addListener('ready', () => { 229 | player.togglePlay(); // Priming the playhead 230 | instance.checkPlayHead(); 231 | }); 232 | }; 233 | 234 | IFrameAPI.createController(element, options, callback); 235 | }; 236 | } 237 | 238 | // Extract episode ID from the Spotify URL 239 | extractEpisodeID(url) { 240 | const match = url.match(/episode\/(.+)$/); 241 | return match ? match[1] : null; 242 | } 243 | 244 | // Get the current time of the Spotify player 245 | getTime() { 246 | return Promise.resolve(this.currentTime); 247 | } 248 | 249 | // Set the current time of the Spotify player 250 | setTime(seconds) { 251 | this.player.seek(seconds); 252 | } 253 | 254 | // Play the Spotify track 255 | play() { 256 | this.player.play(); 257 | this.paused = false; 258 | } 259 | 260 | // Pause the Spotify track 261 | pause() { 262 | this.player.togglePlay(); 263 | this.paused = true; 264 | } 265 | } 266 | 267 | // Mapping player types to their respective classes 268 | const hyperaudioPlayerOptions = { 269 | "native": NativePlayer, 270 | "soundcloud": SoundCloudPlayer, 271 | "youtube": YouTubePlayer, 272 | "videojs": VideoJSPlayer, 273 | "vimeo": VimeoPlayer, 274 | "spotify": SpotifyPlayer 275 | }; 276 | 277 | // Factory function to create player instances 278 | function hyperaudioPlayer(playerType, instance) { 279 | if (playerType) { 280 | return new hyperaudioPlayerOptions[playerType](instance); 281 | } else { 282 | console.warn("HYPERAUDIO LITE WARNING: data-player-type attribute should be set on player if not native, e.g., SoundCloud, YouTube, Vimeo, VideoJS"); 283 | } 284 | } 285 | 286 | // Main class for HyperaudioLite functionality 287 | class HyperaudioLite { 288 | constructor(transcriptId, mediaElementId, minimizedMode, autoscroll, doubleClick, webMonetization, playOnClick) { 289 | this.transcript = document.getElementById(transcriptId); 290 | this.init(mediaElementId, minimizedMode, autoscroll, doubleClick, webMonetization, playOnClick); 291 | 292 | // Ensure correct binding for class methods 293 | this.preparePlayHead = this.preparePlayHead.bind(this); 294 | this.pausePlayHead = this.pausePlayHead.bind(this); 295 | this.setPlayHead = this.setPlayHead.bind(this); 296 | this.checkPlayHead = this.checkPlayHead.bind(this); 297 | this.clearTimer = this.clearTimer.bind(this); 298 | } 299 | 300 | // Initialize the HyperaudioLite instance 301 | init(mediaElementId, minimizedMode, autoscroll, doubleClick, webMonetization, playOnClick) { 302 | this.setupTranscriptHash(); 303 | this.setupPopover(); 304 | this.setupPlayer(mediaElementId); 305 | this.setupTranscriptWords(); 306 | this.setupEventListeners(doubleClick, playOnClick); 307 | this.setupInitialPlayHead(); 308 | this.minimizedMode = minimizedMode; 309 | this.autoscroll = autoscroll; 310 | this.webMonetization = webMonetization; 311 | } 312 | 313 | // Setup hash for transcript selection 314 | setupTranscriptHash() { 315 | const windowHash = window.location.hash; 316 | const hashVar = windowHash.substring(1, windowHash.indexOf('=')); 317 | 318 | if (hashVar === this.transcript.id) { 319 | this.hashArray = windowHash.substring(this.transcript.id.length + 2).split(','); 320 | } else { 321 | this.hashArray = []; 322 | } 323 | } 324 | 325 | // Setup the popover for text selection 326 | setupPopover() { 327 | if (typeof popover !== 'undefined') { 328 | this.transcript.addEventListener('mouseup', () => { 329 | const selection = window.getSelection(); 330 | const popover = document.getElementById('popover'); 331 | let selectionText; 332 | 333 | if (selection.toString().length > 0) { 334 | selectionText = selection.toString().replaceAll("'", "`"); 335 | const range = selection.getRangeAt(0); 336 | const rect = range.getBoundingClientRect(); 337 | 338 | popover.style.left = `${rect.left + window.scrollX}px`; 339 | popover.style.top = `${rect.bottom + window.scrollY}px`; 340 | popover.style.display = 'block'; 341 | 342 | const mediaFragment = this.getSelectionMediaFragment(); 343 | 344 | if (mediaFragment) { 345 | document.location.hash = mediaFragment; 346 | } 347 | } else { 348 | popover.style.display = 'none'; 349 | } 350 | 351 | const popoverBtn = document.getElementById('popover-btn'); 352 | popoverBtn.addEventListener('click', (e) => { 353 | popover.style.display = 'none'; 354 | let cbText = `${selectionText} ${document.location}`; 355 | navigator.clipboard.writeText(cbText); 356 | 357 | const dialog = document.getElementById("clipboard-dialog"); 358 | document.getElementById("clipboard-text").innerHTML = cbText; 359 | dialog.showModal(); 360 | 361 | const confirmButton = document.getElementById("clipboard-confirm"); 362 | confirmButton.addEventListener("click", () => dialog.close()); 363 | 364 | e.preventDefault(); 365 | return false; 366 | }); 367 | }); 368 | } 369 | } 370 | 371 | // Setup the media player 372 | setupPlayer(mediaElementId) { 373 | this.player = document.getElementById(mediaElementId); 374 | const mediaSrc = this.transcript.querySelector('[data-media-src]'); 375 | if (mediaSrc) { 376 | this.player.src = mediaSrc.getAttribute('data-media-src'); 377 | } 378 | 379 | if (this.player.tagName === 'VIDEO' || this.player.tagName === 'AUDIO') { 380 | this.playerType = 'native'; 381 | } else { 382 | this.playerType = this.player.getAttribute('data-player-type'); 383 | } 384 | 385 | this.myPlayer = hyperaudioPlayer(this.playerType, this); 386 | } 387 | 388 | // Setup the transcript words 389 | setupTranscriptWords() { 390 | const words = this.transcript.querySelectorAll('[data-m]'); 391 | this.wordArr = this.createWordArray(words); 392 | this.parentTag = words[0].parentElement.tagName; 393 | this.parentElements = this.transcript.getElementsByTagName(this.parentTag); 394 | } 395 | 396 | // Setup event listeners for interactions 397 | setupEventListeners(doubleClick, playOnClick) { 398 | this.minimizedMode = false; 399 | this.autoscroll = false; 400 | this.doubleClick = doubleClick; 401 | this.webMonetization = false; 402 | this.playOnClick = playOnClick; 403 | this.highlightedText = false; 404 | this.start = null; 405 | 406 | if (this.autoscroll) { 407 | this.scroller = window.Velocity || window.jQuery.Velocity; 408 | } 409 | 410 | const playHeadEvent = doubleClick ? 'dblclick' : 'click'; 411 | this.transcript.addEventListener(playHeadEvent, this.setPlayHead.bind(this), false); 412 | this.transcript.addEventListener(playHeadEvent, this.checkPlayHead.bind(this), false); 413 | } 414 | 415 | // Setup initial playhead position based on URL hash 416 | setupInitialPlayHead() { 417 | this.start = this.hashArray[0]; 418 | if (!isNaN(parseFloat(this.start))) { 419 | this.highlightedText = true; 420 | let indices = this.updateTranscriptVisualState(this.start); 421 | if (indices.currentWordIndex > 0) { 422 | this.scrollToParagraph(indices.currentParentElementIndex, indices.currentWordIndex); 423 | } 424 | } 425 | 426 | this.end = this.hashArray[1]; 427 | //TODO convert to binary search for below for quicker startup 428 | if (this.start && this.end) { 429 | const words = this.transcript.querySelectorAll('[data-m]'); 430 | for (let i = 1; i < words.length; i++) { 431 | let startTime = parseInt(words[i].getAttribute('data-m')) / 1000; 432 | let wordStart = (Math.round(startTime * 100) / 100).toFixed(2); 433 | if (wordStart >= parseFloat(this.start) && parseFloat(this.end) > wordStart) { 434 | words[i].classList.add('share-match'); 435 | } 436 | } 437 | } 438 | } 439 | 440 | // Create an array of words with metadata from the transcript 441 | createWordArray(words) { 442 | return Array.from(words).map(word => { 443 | const m = parseInt(word.getAttribute('data-m')); 444 | let p = word.parentNode; 445 | while (p !== document) { 446 | if (['p', 'figure', 'ul'].includes(p.tagName.toLowerCase())) { 447 | break; 448 | } 449 | p = p.parentNode; 450 | } 451 | word.classList.add('unread'); 452 | return { n: word, m, p }; 453 | }); 454 | } 455 | 456 | getSelectionRange = () => { 457 | const selection = window.getSelection(); 458 | if (selection.rangeCount === 0) return null; 459 | 460 | const range = selection.getRangeAt(0); 461 | 462 | // Helper function to get the closest span 463 | function getClosestSpan(node) { 464 | while (node && node.nodeType !== Node.ELEMENT_NODE) { 465 | node = node.parentNode; 466 | } 467 | return node.closest('[data-m]'); 468 | } 469 | 470 | // Get all relevant spans 471 | const allSpans = Array.from(this.transcript.querySelectorAll('[data-m]')); 472 | 473 | // Find the first and last span that contain selected text 474 | let startSpan = null; 475 | let endSpan = null; 476 | let selectedText = range.toString(); 477 | let trimmedSelectedText = selectedText.trim(); 478 | 479 | for (let span of allSpans) { 480 | if (range.intersectsNode(span) && span.textContent.trim() !== '') { 481 | if (!startSpan) startSpan = span; 482 | endSpan = span; 483 | } 484 | } 485 | 486 | if (!startSpan || !endSpan) return null; 487 | 488 | // Adjust start span if selection starts with a space 489 | let startIndex = allSpans.indexOf(startSpan); 490 | while (selectedText.startsWith(' ') && startIndex < allSpans.length - 1) { 491 | startIndex++; 492 | startSpan = allSpans[startIndex]; 493 | selectedText = selectedText.slice(1); 494 | } 495 | 496 | // Calculate start time 497 | let startTime = parseInt(startSpan.dataset.m) / 1000; 498 | 499 | // Calculate end time 500 | 501 | let duration = 0; 502 | if (endSpan.dataset.d) { 503 | duration = parseInt(endSpan.dataset.d); 504 | } else { 505 | // when no duration exists default to 1 second 506 | duration = 1000; 507 | } 508 | 509 | let endTime = (parseInt(endSpan.dataset.m) + duration) / 1000; 510 | 511 | // Format to seconds at 2 decimal place precision 512 | let startTimeFormatted = (Math.round(startTime * 100) / 100).toFixed(2); 513 | let endTimeFormatted = (Math.round(endTime * 100) / 100).toFixed(2); 514 | 515 | // Only return a range if there's actually selected text (excluding only spaces) 516 | return trimmedSelectedText ? `${startTimeFormatted},${endTimeFormatted}` : null; 517 | } 518 | 519 | getSelectionMediaFragment = () => { 520 | let range = this.getSelectionRange(); 521 | if (range === null) { 522 | return null; 523 | } 524 | console.log(range); 525 | return (this.transcript.id + '=' +range); 526 | } 527 | 528 | // Set the playhead position in the media player based on the transcript 529 | setPlayHead(e) { 530 | const target = e.target || e.srcElement; 531 | this.highlightedText = false; 532 | this.clearActiveClasses(); 533 | 534 | if (this.myPlayer.paused && target.dataset.m) { 535 | target.classList.add('active'); 536 | target.parentNode.classList.add('active'); 537 | } 538 | 539 | const timeSecs = parseInt(target.dataset.m) / 1000; 540 | this.updateTranscriptVisualState(timeSecs); 541 | 542 | if (!isNaN(timeSecs)) { 543 | this.end = null; 544 | this.myPlayer.setTime(timeSecs); 545 | if (this.playOnClick) { 546 | this.myPlayer.play(); 547 | } 548 | } 549 | } 550 | 551 | // Clear the active classes from the transcript 552 | clearActiveClasses() { 553 | const activeElements = Array.from(this.transcript.getElementsByClassName('active')); 554 | activeElements.forEach(e => e.classList.remove('active')); 555 | } 556 | 557 | // Prepare the playhead for playback 558 | preparePlayHead() { 559 | this.myPlayer.paused = false; 560 | this.checkPlayHead(); 561 | } 562 | 563 | // Pause the playhead 564 | pausePlayHead() { 565 | this.clearTimer(); 566 | this.myPlayer.paused = true; 567 | } 568 | 569 | // Check the playhead position and update the transcript 570 | checkPlayHead() { 571 | this.clearTimer(); 572 | 573 | (async () => { 574 | this.currentTime = await this.myPlayer.getTime(); 575 | if (this.highlightedText) { 576 | this.currentTime = this.start; 577 | this.myPlayer.setTime(this.currentTime); 578 | this.highlightedText = false; 579 | } 580 | this.checkStatus(); 581 | })(); 582 | } 583 | 584 | // Clear the timer for the playhead 585 | clearTimer() { 586 | if (this.timer) { 587 | clearTimeout(this.timer); 588 | this.timer = null; 589 | } 590 | } 591 | 592 | // Scroll to the paragraph containing the current word 593 | scrollToParagraph(currentParentElementIndex, index) { 594 | const scrollNode = this.wordArr[index - 1].n.closest('p') || this.wordArr[index - 1].n; 595 | 596 | if (currentParentElementIndex !== this.parentElementIndex) { 597 | if (this.autoscroll && typeof this.scroller !== 'undefined') { 598 | if (scrollNode) { 599 | this.scroller(scrollNode, 'scroll', { 600 | container: this.scrollerContainer, 601 | duration: this.scrollerDuration, 602 | delay: this.scrollerDelay, 603 | offset: this.scrollerOffset, 604 | }); 605 | } else { 606 | this.wordArr = this.createWordArray(this.transcript.querySelectorAll('[data-m]')); 607 | this.parentElements = this.transcript.getElementsByTagName(this.parentTag); 608 | } 609 | } 610 | this.parentElementIndex = currentParentElementIndex; 611 | } 612 | } 613 | 614 | // Check the status of the playhead and update the transcript 615 | checkStatus() { 616 | if (!this.myPlayer.paused) { 617 | if (this.end && parseInt(this.end) < parseInt(this.currentTime)) { 618 | this.myPlayer.pause(); 619 | this.end = null; 620 | } else { 621 | const indices = this.updateTranscriptVisualState(this.currentTime); 622 | const index = indices.currentWordIndex; 623 | if (index > 0) { 624 | this.scrollToParagraph(indices.currentParentElementIndex, index); 625 | } 626 | 627 | if (this.minimizedMode) { 628 | const elements = this.transcript.querySelectorAll('[data-m]'); 629 | let currentWord = ''; 630 | let lastWordIndex = this.wordIndex; 631 | 632 | for (let i = 0; i < elements.length; i++) { 633 | if (elements[i].classList.contains('active')) { 634 | currentWord = elements[i].innerHTML; 635 | this.wordIndex = i; 636 | } 637 | } 638 | 639 | if (this.wordIndex !== lastWordIndex) { 640 | document.title = currentWord; 641 | } 642 | } 643 | 644 | if (this.webMonetization === true) { 645 | //check for payment pointer 646 | let activeElements = this.transcript.getElementsByClassName('active'); 647 | let paymentPointer = this.checkPaymentPointer(activeElements[activeElements.length - 1]); 648 | 649 | if (paymentPointer !== null) { 650 | let metaElements = document.getElementsByTagName('meta'); 651 | let wmMeta = document.querySelector("meta[name='monetization']"); 652 | if (wmMeta === null) { 653 | wmMeta = document.createElement('meta'); 654 | wmMeta.name = 'monetization'; 655 | wmMeta.content = paymentPointer; 656 | document.getElementsByTagName('head')[0].appendChild(wmMeta); 657 | } else { 658 | wmMeta.name = 'monetization'; 659 | wmMeta.content = paymentPointer; 660 | } 661 | } 662 | } 663 | 664 | let interval = 0; 665 | if (this.wordArr[index]) { 666 | interval = this.wordArr[index].n.getAttribute('data-m') - this.currentTime * 1000; 667 | } 668 | 669 | this.timer = setTimeout(() => this.checkPlayHead(), interval + 1); 670 | } 671 | } else { 672 | this.clearTimer(); 673 | } 674 | } 675 | 676 | checkPaymentPointer = element => { 677 | let paymentPointer = null; 678 | 679 | if (typeof(element) != "undefined") { 680 | paymentPointer = element.getAttribute('data-wm'); 681 | } 682 | 683 | if (paymentPointer !== null) { 684 | return paymentPointer; 685 | } else { 686 | let parent = null; 687 | 688 | if (typeof element !== 'undefined') { 689 | parent = element.parentElement; 690 | } 691 | 692 | if (parent === null) { 693 | return null; 694 | } else { 695 | return this.checkPaymentPointer(parent); 696 | } 697 | } 698 | } 699 | 700 | // Update the visual state of the transcript based on the current time 701 | updateTranscriptVisualState(currentTime) { 702 | let index = 0; 703 | let words = this.wordArr.length - 1; 704 | 705 | while (index <= words) { 706 | const guessIndex = index + ((words - index) >> 1); 707 | const difference = this.wordArr[guessIndex].m / 1000 - currentTime; 708 | 709 | if (difference < 0) { 710 | index = guessIndex + 1; 711 | } else if (difference > 0) { 712 | words = guessIndex - 1; 713 | } else { 714 | index = guessIndex; 715 | break; 716 | } 717 | } 718 | 719 | this.wordArr.forEach((word, i) => { 720 | const classList = word.n.classList; 721 | const parentClassList = word.n.parentNode.classList; 722 | 723 | if (i < index) { 724 | classList.add('read'); 725 | classList.remove('unread', 'active'); 726 | parentClassList.remove('active'); 727 | } else { 728 | classList.add('unread'); 729 | classList.remove('read'); 730 | } 731 | }); 732 | 733 | this.parentElements = this.transcript.getElementsByTagName(this.parentTag); 734 | Array.from(this.parentElements).forEach(el => el.classList.remove('active')); 735 | 736 | if (index > 0) { 737 | if (!this.myPlayer.paused) { 738 | this.wordArr[index - 1].n.classList.add('active'); 739 | } 740 | this.wordArr[index - 1].n.parentNode.classList.add('active'); 741 | } 742 | 743 | const currentParentElementIndex = Array.from(this.parentElements).findIndex(el => el.classList.contains('active')); 744 | 745 | return { 746 | currentWordIndex: index, 747 | currentParentElementIndex 748 | }; 749 | } 750 | } 751 | 752 | // Export for testing or module usage 753 | if (typeof module !== 'undefined' && module.exports) { 754 | module.exports = { HyperaudioLite }; 755 | } -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | === Hyperaudio === 2 | Contributors: Maboas 3 | Donate link: https://patreon.com/hyperaudio 4 | Tags: Podcasts, Captions, Transcripts, Interactive Transcripts, Accessibility, Media, Audio, Video, Subtitles 5 | Requires at least: 3.1 6 | Tested up to: 6.3 7 | Stable tag: 1.0 8 | Requires PHP: 7.0 9 | License: GPLv2 10 | License URI: http://www.gnu.org/licenses/gpl-2.0.html 11 | 12 | Associate interactive transcripts with your audiovisual content and make your media more accessible to people and search engines. 13 | 14 | == Description == 15 | 16 | Allows you to import and convert data from a number of popular speech-to-text providers and tools. 17 | 18 | The result is an interactive transcript where words "light up" as they are spoken. 19 | 20 | Clicking on words in a transcript takes you directly to equivalent part of your media, while selecting a passage of text creates a handy link back to the highlighted part – great for sharing! 21 | 22 | Currently the transcript generator (provided in the settings) can convert from the following speech-to-text outputs: 23 | 24 | * [OpenEditor](https://github.com/OpenEditor/openeditor/) JSON 25 | * [Speechmatics](https://speechmatics.com) JSON 26 | * [Google Speech-to-text](https://cloud.google.com/speech-to-text/) JSON 27 | * [Gentle](http://lowerquality.com/gentle/) JSON 28 | * [.srt formatted](https://en.wikipedia.org/wiki/SubRip) captions 29 | 30 | Two views of the resultant transcript are provided... 31 | 32 | = Hypertranscript View = 33 | 34 | A Hypertranscript is an [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) representation of a media file's spoken audio. This format is ready to be pasted between the Hyperaudio shortcode. Note that since Hypertranscripts create timings and HTML is a format that is both human and machine readable, timings and words can be tweaked by editing this HTML. 35 | 36 | = Rendered View = 37 | 38 | The rendered view is how the text itself will look once viewed as an Interactive Transcript. Words can be edited from the rendered view but timings of words may not be maintained if you (say) replace two words with one, or paste content into the text. 39 | 40 | Once you are happy with your text you need to locate your source media and you're ready to create an Interactive Transcript within your post using the `[hyperaudio]` shortcode. 41 | 42 | Something like this : 43 | 44 | ``[hyperaudio src="link-to-media.mp4"] 45 | 46 | ``
47 | ``
48 | ``

49 | `` This 50 | `` interactive 51 | `` transcript 52 | `` is 53 | `` great! 54 | ``

55 | ``
56 | ``
57 | 58 | ``[/hyperaudio] 59 | 60 | You can specify a number of parameters including player type. So far we support the following players: 61 | 62 | * YouTube 63 | * SoundCloud 64 | * Vimeo 65 | * Videojs 66 | 67 | As well as native mp4 and mp3 files. 68 | 69 | = Captions = 70 | 71 | The module also creates captions for your videos. Useful when viewing content in fullscreen. 72 | 73 | = Accessibility = 74 | 75 | All in all we make audiovisual media more accessible. 76 | 77 | Accessible to those with hearing difficulties or people consuming content which is not necessarily in their first language. 78 | 79 | Accessible to those choosing to view content with the audio off. Accessible to search engines so that content can be indexed and more easily discovered. 80 | 81 | = Flexibility = 82 | 83 | You are not limited to creating Interactive Transcripts. You can format the HTML any way you want. Hyperaudio can be used to create "chapter points". Some have even used it to define songs and artists within a musical mix. 84 | 85 | = Explainer Videos = 86 | 87 | * [How to use the Hyperaudio Wordpress Interactive Transcript – Part 1](https://youtu.be/3Qpq8kj4PxM) 88 | 89 | * [How to use the Hyperaudio Wordpress Interactive Transcript – Part 2](https://youtu.be/vIXHCYYSFM0) 90 | 91 | * [How to use the Hyperaudio Wordpress Interactive Transcript – Part 3](https://youtu.be/ly08N9S1ZlE) 92 | 93 | * [Web Monetization in the Hyperaudio Wordpress Interactive Transcript](https://youtu.be/8kRNh8iBkVk) 94 | 95 | == Screenshots == 96 | 97 | native_audio.png 98 | native_video.png 99 | selecting_shortcode.png 100 | sharing_excerpt.png 101 | shortcode_usage.png 102 | soundcloud_player.png 103 | transcript_converter.png 104 | transcript_converter_howto.png 105 | transcript_converter_howto_customize.png 106 | transcript_converter_interface.png 107 | transcript_converter_markup.png 108 | upload_media.png 109 | 110 | 111 | == Frequently Asked Questions == 112 | 113 | = How do I make my own Interactive Transcript? = 114 | 115 | Probably the easiest way is to use the [Hyperaudio Lite Editor](https://hyperaudio.github.io/hyperaudio-lite-editor/). 116 | 117 | Alternatively you can use the [OpenEditor](https://github.com/OpenEditor/openeditor/) (transcript editor) which you can find on GitHub. 118 | 119 | Or you can use Google Speech-to-Text Service, Speechmatics or Gentle's aligner (especially if you already have the transcript and just want to add timings). 120 | 121 | You can also convert captions or subtitles in `.srt` format to timed transcripts, although exact word timing cannot be ensured in that case. 122 | 123 | = Can I change the transcript's content? = 124 | 125 | Yes. The transcript is editable. Changing one word will generally maintain that word's timing, replacing more than one word may result in more than one word with the same timing. 126 | 127 | Note – as transcripts are represented as HTML, you can edit the HTML directly should you need to refine text or styling. 128 | 129 | = I'd like to contribute. Where is the repository? = 130 | 131 | Our code is open source and we're always looking for help. You can find the code and discussion at [github.com/hyperaudio/wordpress-hyperaudio](https://github.com/hyperaudio/wordpress-hyperaudio/). --------------------------------------------------------------------------------