HTML5 Audio/Video Keyboard Shortcuts With OSD

Adds keyboard shortcuts for controlling HTML5 media player (audio/video) with OSD support. Seek media to 0%, 5%, 10%, ..., or 95%. Rewind and fast fordward media by 30 seconds, 1 minute, and 5 minutes. Change media speed even beyond YouTube's speed limit. Change audio volume to 20%, 40%, 60%, 80%, or 100%. Change video aspect ratio for TV and letterbox content (for widescreen monitors).

当前为 2024-05-26 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HTML5 Audio/Video Keyboard Shortcuts With OSD
  3. // @namespace https://greasyfork.org/en/users/85671-jcunews
  4. // @version 1.3.19
  5. // @license AGPLv3
  6. // @author jcunews
  7. // @description Adds keyboard shortcuts for controlling HTML5 media player (audio/video) with OSD support. Seek media to 0%, 5%, 10%, ..., or 95%. Rewind and fast fordward media by 30 seconds, 1 minute, and 5 minutes. Change media speed even beyond YouTube's speed limit. Change audio volume to 20%, 40%, 60%, 80%, or 100%. Change video aspect ratio for TV and letterbox content (for widescreen monitors).
  8. // @match *://*/*
  9. // @grant none
  10. // @run-at document-start
  11. // ==/UserScript==
  12.  
  13. /*
  14. Notes:
  15.  
  16. - Some shortcuts won't work on non US keyboards. Non US keyboard users will need to manually edit the keys in the script.
  17. - In YouTube, if the video speed is below 0.25x or above 2x, the YouTube setting display will be capped to 0.1x or 2x.
  18. - Web browser video speeds: Firefox = 0.25 to 5.0; Chrome = 0.1 to 16.0.
  19.  
  20.  
  21. Keyboard Shortcuts:
  22.  
  23. CTRL+, = Rewind media by 1/30th second
  24. CTRL+. = Fast forward media by 1/30th second
  25. CTRL+SHIFT+/ = Next frame (when paused; Firefox only)
  26. SHIFT+LEFT = Rewind media by 30 seconds
  27. SHIFT+RIGHT = Fast forward media by 30 seconds
  28. CTRL+LEFT = Rewind media by 1 minute
  29. CTRL+RIGHT = Fast forward media by 1 minute
  30. CTRL+SHIFT+LEFT = Rewind media by 5 minutes
  31. CTRL+SHIFT+RIGHT = Fast forward media by 5 minutes
  32. CTRL+/ = Fast forward media by 1.5 minutes
  33. 0 to 9 = Seek media to 0%, 10%, 20%,...90%
  34. SHIFT+0 to SHIFT+9 = Seek media to 5%, 15%, 25%,...95%
  35. CTRL+1 to CTRL+5 = Change audio volume to 20%, 40%, 60$, 80%, 100%
  36. CTRL+[ = Decrease media speed by 0.2x (by default)
  37. CTRL+] = Increase media speed by 0.2x (by default)
  38. CTRL+; = Reset media speed
  39. CTRL+' = Change custom media speed
  40. CTRL+\ = Change unit of media speed increment/decrement
  41.  
  42. For Widescreen Video Viewport:
  43. CTRL+6 = Change video aspect ratio for widescreen content. Fix widescreen content shrunk to 4:3 TV format.
  44. CTRL+7 = Change video aspect ratio for letterbox content. Fix 4:3 letterbox content stretched to widescreen format.
  45. CTRL+8 = Change video aspect ratio for TV content. Fix 4:3 TV content stretched to widescreen format.
  46.  
  47. For 4:3 TV Video Viewport:
  48. CTRL+SHIFT+6 = Change video aspect ratio for ultra widescreen content. Fix ultra widescreen content compressed into 4:3 TV format.
  49. CTRL+SHIFT+7 = Zoom 4:3 letterbox content to remove half of top+bottom borders, but also remove left+right content a little.
  50. This can also be used to half-zoom ultra widescreen content on widescreen viewport. i.e. half-zoom of CTRL+6.
  51. CTRL+SHIFT+8 = Change video aspect ratio for widescreen content. Fix widescreen content compressed into 4:3 TV format.
  52.  
  53. For Any Video Viewport:
  54. CTRL+9 = Reset video aspect ratio
  55. ALT+S = Take screenshot if current video frame (in its original size and aspect ratio)
  56. */
  57.  
  58. ((eleOSD, osdTimer) => {
  59.  
  60. //=== CONFIGURATION BEGIN ===
  61.  
  62. //Video speed increment/decrement unit.
  63. var incrementUnit = 0.2;
  64.  
  65. //Duration (in milliseconds) to display On Screen Display (OSD) when changing playback rate. Set to zero or less to disable.
  66. var osdTimeout = 3000;
  67.  
  68. //Image format for video frame screenshot
  69. var imageFormat = "jpeg"; //can be jpeg or png
  70.  
  71. //Keyboard shortcuts.
  72. //key = Key name. String type if single shortcut, or array of string if multiple shortcut (for single function multiple shortcuts).
  73. // Each key name can either be the character which is produced by the key (e.g. `A`, `4`, `*`, etc.),
  74. // or the code name for the key (e.g. `Digit2`, `BracketLeft`, etc.).
  75. // When SHIFT modifier is used with keys which produces a character, key code name should be used if the character is important.
  76. // A list of key code names can be found here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values
  77. //caseSensitive = `true` if key name is case-sensitive. If omitted, the default is not case-sensitive.
  78. //modifiers = Any combinations of uppercased "C", "S", and "A", for Ctrl, Shift, and Alt keys. If omitted, the default is "".
  79. //videoOnly = Apply only if a video element exist. If omitted, the default is always apply.
  80. //func = Function to be called. Function arguments: elementObj, pressedKey, matchingKeyIndex
  81. // elementObj : The video/audio element.
  82. // pressedKey : The pressed key. Uppercased if matching keyboard shortcut is not case-sensitive.
  83. // matchingKeyIndex: If multiple keys is specified, the index of the key array. `null` otherwise.
  84. // keyObject : The matching keyboard shortcut object in `keys` array.
  85. var keys = [
  86. { //ctrl+space: seek media to next frame (only when paused. firefox only)
  87. key: " ", modifiers: "C",
  88. func: (ele, key) => ele.seekToNextFrame && ele.seekToNextFrame()
  89. },
  90. { //0 to 9: seek media to 0%,10%,20%,...90%
  91. key: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], modifiers: "",
  92. func: (ele, key, keyIndex) => ele.currentTime = keyIndex / 10 * ele.duration
  93. },
  94. { //shift+0 to shift+9: seek media to 5%,15%,25%,...95%
  95. key: [")", "!", "@", "#", "$", "%", "^", "&", "*", "("], modifiers: "S",
  96. func: (ele, key, keyIndex) => ele.currentTime = (keyIndex + 0.5) / 10 * ele.duration
  97. },
  98. { //ctrl+1 to ctrl+5: set audio volume to 20%,40%,60%,80%,100%
  99. key: ["1", "2", "3", "4", "5"], modifiers: "C",
  100. func: (ele, key, keyIndex) => updAudioVolume(ele, (parseInt(key) * 2) / 10)
  101. },
  102. { //shift+left: rewind media by 30 seconds
  103. key: "ArrowLeft", modifiers: "S",
  104. func: (ele, key) => ele.currentTime -= 30
  105. },
  106. { //ctrl+left: rewind media by 1 minute
  107. key: "ArrowLeft", modifiers: "C",
  108. func: (ele, key) => ele.currentTime -= 60
  109. },
  110. { //ctrl+shift+left: rewind media by 5 minutes
  111. key: "ArrowLeft", modifiers: "CS",
  112. func: (ele, key) => ele.currentTime -= 300
  113. },
  114. { //ctrl+,: rewind media by 1/30 second
  115. key: ",", modifiers: "C",
  116. func: (ele, key) => ele.currentTime -= 1/30
  117. },
  118. { //shift+right: fast forward media by 30 seconds
  119. key: "ArrowRight", modifiers: "S",
  120. func: (ele, key) => ele.currentTime += 30
  121. },
  122. { //ctrl+right: fast forward media by 1 minute
  123. key: "ArrowRight", modifiers: "C",
  124. func: (ele, key) => ele.currentTime += 60
  125. },
  126. { //ctrl+shift+right: fast forward media by 5 minutes
  127. key: "ArrowRight", modifiers: "CS",
  128. func: (ele, key) => ele.currentTime += 300
  129. },
  130. { //ctrl+.: fast forward media by 1/30th second
  131. key: ".", modifiers: "C",
  132. func: (ele, key) => ele.currentTime += 1/30
  133. },
  134. { //ctrl+shift+/: next frame (when paused; firefox only)
  135. key: "?", modifiers: "CS",
  136. func: (ele, key) => ele.seekToNextFrame && ele.seekToNextFrame()
  137. },
  138. { //ctrl+/: fast forward media by 1.5 minutes
  139. key: "/", modifiers: "C",
  140. func: (ele, key) => ele.currentTime += 87
  141. },
  142. { //ctrl+[: decrease media speed
  143. key: "[", modifiers: "C",
  144. func: (ele, key) => {
  145. key = ele.playbackRate - incrementUnit;
  146. if (key < 0.1) {
  147. key = 0.1;
  148. } else if ((key < 1) && (ele.playbackRate > 1)) key = 1;
  149. updVideoSpeed(ele, key);
  150. }
  151. },
  152. { //ctrl+]: increase media speed
  153. key: "]", modifiers: "C",
  154. func: (ele, key) => {
  155. key = ele.playbackRate + incrementUnit;
  156. if (key > 16) {
  157. key = 16;
  158. } else if ((key > 1) && (ele.playbackRate < 1)) key = 1;
  159. updVideoSpeed(ele, key);
  160. }
  161. },
  162. { //ctrl+;: reset media speed to 1x
  163. key: ";", modifiers: "C",
  164. func: (ele, key) => updVideoSpeed(ele, 1)
  165. },
  166. { //ctrl+': use custom media speed
  167. key: "'", modifiers: "C",
  168. func: (ele, key) => {
  169. if ((key = prompt("Enter media speed from 0.1 to 16 (inclusive).\ne.g.: 1 = Normal, 0.5 = Half, 2 = Double, 3 = Triple, etc.", ele.playbackRate)) === null) return;
  170. if (isNaN(key = parseFloat(key.trim()))) {
  171. alert("Input must be a number.");
  172. return;
  173. }
  174. updVideoSpeed(ele, (key = parseFloat(key.toFixed(1))) < 0.1 ? 0.1 : (key > 16 ? 16 : key));
  175. }
  176. },
  177. { //ctrl+\: change unit of media speed increment/decrement
  178. key: "\\", modifiers: "C",
  179. func: (ele, key) => {
  180. if ((key = prompt("Enter unit of media speed increment/decrement from 0.1 to 4 (inclusive).", incrementUnit)) === null) return;
  181. if (!isNaN(key = parseFloat(key.trim()))) {
  182. incrementUnit = (key = parseFloat(key.toFixed(1))) < 0.1 ? 0.1 : (key > 4 ? 4 : key);
  183. } else alert("Input must be a number.");
  184. }
  185. },
  186. { //ctrl+6: Widescreen aspect ratio
  187. key: "6", modifiers: "C", videoOnly: true,
  188. func: (ele, key) => updVideoAspect("scaleX(1.3333)", "Widescreen")
  189. },
  190. { //ctrl+7: Letterbox aspect ratio
  191. key: "7", modifiers: "C", videoOnly: true,
  192. func: (ele, key) => updVideoAspect("scaleY(1.3333)", "Letterbox")
  193. },
  194. { //ctrl+8: TV aspect ratio
  195. key: "8", modifiers: "C", videoOnly: true,
  196. func: (ele, key) => updVideoAspect("scaleX(0.75)", "TV")
  197. },
  198. { //ctrl+shift+6: Ultra widescreen aspect ratio
  199. key: "Digit6", modifiers: "CS", videoOnly: true,
  200. func: (ele, key) => updVideoAspect("scaleY(0.7168)", "Ultra Widescreen")
  201. },
  202. { //ctrl+shift+7: Half-zoom letterbox
  203. key: "Digit7", modifiers: "CS", videoOnly: true,
  204. func: (ele, key) => updVideoAspect("scale(1.1666)", "Letterbox Half-Zoom")
  205. },
  206. { //ctrl+shift+8: Widescreen on TV
  207. key: "Digit8", modifiers: "CS", videoOnly: true,
  208. func: (ele, key) => updVideoAspect("scaleY(0.5625)", "Widescreen On TV")
  209. },
  210. { //ctrl+9: reset video aspect ratio
  211. key: "9", modifiers: "C", videoOnly: true,
  212. func: (ele, key) => updVideoAspect("", "Reset")
  213. },
  214. { //alt+s: take screenshot of current video frame
  215. key: "S", modifiers: "A", videoOnly: true,
  216. func: (ele, key, cv, a) => {
  217. cv = document.createElement("CANVAS");
  218. if (cv.width = ele.videoWidth) {
  219. cv.height = ele.videoHeight;
  220. cv.getContext("2d").drawImage(ele, 0, 0);
  221. a = document.createElement("A");
  222. a.href = cv.toDataURL("image/" + imageFormat);
  223. a.download = `video_frame_${ele.currentTime}.${imageFormat === "jpeg" ? "jpg" : imageFormat}`;
  224. a.style.display = "none";
  225. document.body.appendChild(a).click();
  226. return a.remove()
  227. }
  228. }
  229. }
  230. ];
  231. keys.forEach((k, s, m) => {
  232. if ((k.modifiers === undefined) || !k.modifiers.toUpperCase) k.modifiers = "";
  233. s = k.modifiers.toUpperCase();
  234. k.modifiers = {ctrl: s.includes("C"), shift: s.includes("S"), alt: s.includes("A")}
  235. });
  236.  
  237. //=== CONFIGURATION END ===
  238.  
  239. function showOSD(s) {
  240. if (osdTimeout < 0) return;
  241. if (eleOSD) {
  242. eleOSD.textContent = s;
  243. } else {
  244. eleOSD = document.createElement("DIV");
  245. eleOSD.style.cssText = "position:fixed;z-index:999999999;right:.5rem;bottom:.5rem;margin:0;padding:.2rem .5rem .1rem .5rem;width:auto;height:auto;font:normal 16pt/normal sans-serif;background:#444;color:#fff";
  246. eleOSD.textContent = s;
  247. document.body.appendChild(eleOSD);
  248. }
  249. clearTimeout(osdTimer);
  250. osdTimer = setTimeout(() => {
  251. eleOSD.remove();
  252. eleOSD = null;
  253. }, osdTimeout);
  254. }
  255.  
  256. function stopEvent(ev) {
  257. ev.preventDefault();
  258. ev.stopPropagation();
  259. ev.stopImmediatePropagation();
  260. }
  261.  
  262. function updVideoSpeed(ele, spd, e) {
  263. // if ((location.hostname === "www.youtube.com") && (e = ele.parentNode.parentNode).setPlaybackRate && (spd >= 0.25) && (spd <= 2)) {
  264. // e.setPlaybackRate(spd = parseFloat(spd.toFixed(1)));
  265. // } else ele.playbackRate = spd = parseFloat(spd.toFixed(1));
  266. ele.playbackRate = spd = parseFloat(spd.toFixed(1));
  267. showOSD("Speed " + spd + "x");
  268. }
  269.  
  270. function updVideoAspect(asp, label, s) {
  271. if (!(s = document.getElementById("vidAspOvr"))) document.body.appendChild(s = document.createElement("STYLE")).id = "vidAspOvr";
  272. s.innerHTML = asp ? `video{transform:${asp}!important}` : "";
  273. showOSD("Ratio: " + label);
  274. }
  275.  
  276. function updAudioVolume(ele, vol, e) {
  277. if ((location.hostname === "www.youtube.com") && (e = ele.parentNode.parentNode).setVolume) {
  278. e.setVolume(vol * 100);
  279. } else ele.volume = vol;
  280. showOSD("Audio " + (vol * 100) + "%");
  281. }
  282.  
  283. function isVisible(ele) {
  284. while (ele && ele.tagName) {
  285. if (getComputedStyle(ele).display === "none") return false;
  286. ele = ele.parentNode
  287. }
  288. return true
  289. }
  290.  
  291. incrementUnit = parseFloat((incrementUnit < 0.1 ? 0.1 : (incrementUnit > 1 ? 1 : incrementUnit)).toFixed(1));
  292. addEventListener("keydown", function(ev, ele, evkey, evcode, kkey) {
  293. if ((!(ele = document.activeElement) || !((ele.contentEditable === "true") || ["BUTTON", "INPUT", "SELECT", "TEXTAREA"].includes(ele.tagName))) && (ele = document.querySelector("video,audio"))) {
  294. keys.some((k, a, i) => {
  295. a = !!k.key.sort;
  296. evkey = k.caseSensitive ? ev.key : ev.key.toUpperCase();
  297. evcode = k.caseSensitive ? ev.code : ev.code.toUpperCase();
  298. kkey = k.caseSensitive ? k.key : (a ? k.key.map(s => s.toUpperCase()) : k.key.toUpperCase());
  299. if (
  300. ((!a && ((kkey === evcode) || (kkey === evkey))) || (a && (((i = kkey.indexOf(evcode)) >= 0) || ((i = kkey.indexOf(evkey)) >= 0)))) &&
  301. (k.modifiers.ctrl === ev.ctrlKey) && (k.modifiers.shift === ev.shiftKey) && (k.modifiers.alt === ev.altKey) &&
  302. (!k.videoOnly || (ele.tagName === "VIDEO")) && (isVisible(ele) || (ele.tagName === "AUDIO"))
  303. ) {
  304. stopEvent(ev);
  305. k.func?.(ele, evkey, a ? i : null, k);
  306. return true;
  307. }
  308. });
  309. }
  310. }, true);
  311.  
  312. })();