chapter_audio.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. function jd_audio(content, startTime) {
  2. var res = content;
  3. Vue.prototype.axios = axios;
  4. window.vm = new Vue({
  5. el: "#audio_app",
  6. data: {
  7. // new start
  8. playIndex: 0, // 开始的段落索引
  9. progressArr: [],
  10. isLoadding: true, // loadding效果
  11. totolStr: "", //页面的总内容, 用户求卷取值
  12. isFirstCut:true,// 第一次文章分段
  13. initArr:[],// 最多内容数组
  14. runningIndex:0,//播放索引卷曲页面使用
  15. isIOS:false,// 是否是IOS
  16. // new end
  17. linsteningProIndex: 0,// 处于下载阶段的段落索引
  18. lisProIndex: 0, //正在听的段落的索引,
  19. lisInnerIndex: 0, // 当前在听的段落的第几部分
  20. needRequest_speed: false, //是否需要重新请求: 调节语速,音色时true
  21. needRequest_sound: false, //是否需要重新请求: 调节语速,音色时true
  22. readType: 0, // 听书1 还是 阅读0
  23. isListening: false,
  24. startFlag: true, //整章第一次加载true
  25. readStartTime: 0, // 开始阅读的时间(毫秒)
  26. newSpeed: 1.0,// 调整后的速度
  27. speed: 1.0, // 播放速度控制
  28. timeout: 0, // 定时时间
  29. timeId: 0,// 定时器id
  30. activeTime: 0,
  31. timearr: [15, 30, 60, 90],// 定时器时间
  32. activeSoundCode: "1",
  33. newVoiceCode: "",
  34. soundarr: [
  35. {
  36. kind: '温柔女声',
  37. code: '0',
  38. },
  39. {
  40. kind: '磁性男声',
  41. code: '1',
  42. },
  43. {
  44. kind: '自然女生',
  45. code: '3',
  46. }
  47. ],// 音色
  48. flags: false,
  49. position: { x: 0, y: 0 },
  50. nx: '', ny: '', dx: '', dy: '', xPum: '', yPum: '',
  51. blog: "", // 全部文章内容
  52. audioSrc: "",
  53. abortMissionsArr: [], // 终止请求函数的存放数组
  54. isFirstRequest: true, // 是否是第一次请求, 第一次jd请求时,只发送一次axios请求, 第二次开始, 批量发送请求
  55. blogArr: [], // 文章内容数组
  56. base64ResultArr: [], // base64响应容器 , key: 请求时的时间戳, val:响应的base64
  57. // baseURL: "https://stream-tts.jd.com/tts/stream", // -dev
  58. // baseURL: "http://stream-tts.jd.com/tts/stream", // -dev
  59. baseURL:"https://stream-tts-dev.jd.com/tts/range", // IOS新接口
  60. appkey: "a42b852ceccba1b98462a43c78ab899a", // JD测试接口免费购买a42b852ceccba1b98462a43c78ab899a
  61. secretKey: "2badb3eb77b3e6eaec78915354df224f", // JD测试接口免费购买2badb3eb77b3e6eaec78915354df224f
  62. timeStamp: 0,
  63. req: {
  64. method: "POST",
  65. // url: "https://stream-tts-dev.jd.com/tts/stream",
  66. url: "https://stream-tts.jd.com/tts/stream",
  67. headers: {
  68. "Service-Type": "synthesis", //固定值, 服务类型
  69. "Request-Id": "2c4dc6e2-e1c5-11e8-a867-040973d59110", // 请求语音串标识码
  70. "Sequence-Id": -1, // 1标识非流式,一次性合成返回
  71. "Protocol": 1, // 通信协议版本号,这里设置固定值1
  72. "Net-State": 1, //客户端网络状态:1:WIFI,2:移动,3:联通,4:电信,5:其他 js获取不到运营商状态, 但是可以拿到网络状态, TODO:用户体验上做提醒"非wifi环境"
  73. "Applicator": 1, // 外部业务
  74. "Property": ""
  75. }
  76. },
  77. headPro: {
  78. "platform": 'Windows&Win64&10.0', // {平台}&{机型}&{系统版本号}
  79. "version": "1.0.0",
  80. "parameters": {
  81. "tt": 0, // UTF-8
  82. "aue": 3, // wav 1:pcm 2:opus 3:mp3
  83. "tim": 1, // "桃桃女声"
  84. "vol": "1.0", //音量
  85. "sp": "1.0", //语速
  86. "sr": 24000 //采样率
  87. }
  88. }
  89. },
  90. methods: {
  91. // new start
  92. // 1 开始请求:设置audiosrc为内容 且添加用户偏好设置
  93. start_new: function () {
  94. var _this = this;
  95. // 创建src赋值给audio
  96. $("#audio_new1").attr({
  97. src: _this.setAudioSrc(_this.progressArr[_this.playIndex])
  98. });
  99. // 如果是IOS,3秒后触发点击屏幕,不然不播放
  100. if(this.isIOS){
  101. window.setTimeout(function(){
  102. try {
  103. // $("#audio_new1")[0].play();
  104. $(".read_main_p").trigger('click');
  105. } catch (error) {
  106. alert("网络异常稍后重试");
  107. window.location.reload();
  108. }
  109. },3000);
  110. }
  111. // 第一次给第一个audio设置src时,加载完成自动播放canplaythrough
  112. // $("#audio_new1")[0].addEventListener("canplay", function (e) {
  113. // var attr = $(this).data("isplaying");
  114. // if (!attr) {
  115. // _this.isLoadding = false; // 隐藏gif
  116. // this.play(); //开始播放
  117. // _this.playIndex+=1;
  118. // window.playingAudioId = "audio_new1"; // 保存正在播放的audio的id
  119. // $("#audio_mask1").toggleClass('menu_box');// 隐藏 语音配置
  120. // $(e.target).siblings('audio').attr({ // 给另一个audiosrc赋值
  121. // src: _this.setAudioSrc(_this.progressArr[_this.playIndex] )
  122. // });
  123. // $(this).data("isplaying", true); // 修改正在播放状态属性,防止第二次预加载完成自动播放
  124. // }
  125. // });
  126. // $('#audio_new1').on('loadstart',function(){
  127. // alert(1)
  128. // })
  129. //canplaythrough
  130. window.disAbale = window.setTimeout(function(){
  131. if(_this.isLoadding){
  132. alert('网络异常,请稍后重试.');
  133. _this.quitAudio_new();
  134. window.clearTimeout(window.disAbale);
  135. }
  136. } , 5000);
  137. $("#audio_new1").on('canplaythrough' , function(e){
  138. window.clearTimeout(window.disAbale);
  139. var attr = $(this).data("isplaying");
  140. if (!attr) {
  141. _this.isLoadding = false; // 隐藏gif
  142. this.play(); //开始播放
  143. _this.playIndex+=1;
  144. window.playingAudioId = "audio_new1"; // 保存正在播放的audio的id
  145. $("#audio_mask1").toggleClass('menu_box');// 隐藏 语音配置
  146. $(e.target).siblings('audio').attr({ // 给另一个audiosrc赋值
  147. src: _this.setAudioSrc(_this.progressArr[_this.playIndex] )
  148. });
  149. $(this).data("isplaying", true); // 修改正在播放状态属性,防止第二次预加载完成自动播放
  150. }
  151. });
  152. },
  153. // 9. 断网检测
  154. scanNetConnect() {
  155. var _this = this;
  156. // 页面进入网状态
  157. if (window.navigator.onLine) {
  158. netType = '1';
  159. } else {
  160. netType = '0';
  161. }
  162. // 监听网络状态
  163. function updateOnlineStatus(event) {
  164. netType = (event.type == 'offline' ? '0' : '1');
  165. if(netType == '0'){
  166. _this.quitAudio_new();
  167. }
  168. }
  169. window.addEventListener('online', updateOnlineStatus);
  170. window.addEventListener('offline', updateOnlineStatus);
  171. },
  172. // 8.获取uuid
  173. generateUUID() {
  174. var d = new Date().getTime();
  175. var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  176. var r = (d + Math.random() * 16) % 16 | 0;
  177. d = Math.floor(d / 16);
  178. return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  179. });
  180. return uuid;
  181. },
  182. // 7.1 页面滚动
  183. setScrollTop(scroll_top) {
  184. document.documentElement.scrollTop = scroll_top;
  185. window.pageYOffset = scroll_top;
  186. document.body.scrollTop = scroll_top;
  187. },
  188. // 7. 读书页面随动 获取所读内容所在的p标签,求卷曲值
  189. pageMove:function(){
  190. var _this = this;
  191. var percent = (_this.runningIndex / _this.initArr.length).toFixed(2);
  192. var scrollTop = ($('.read_main_p').height()*percent).toFixed(2);
  193. _this.setScrollTop(scrollTop);
  194. },
  195. // 6, 修改设置后重新阅读
  196. changeSet: function () {
  197. var _this = this;
  198. _this.isLoadding = true;
  199. if (_this.playIndex == 0) {
  200. var currentIndex = _this.playIndex;
  201. } else {
  202. var currentIndex = _this.playIndex - 1;
  203. }
  204. var newProgressArr = _this.progressArr.slice(currentIndex);
  205. _this.progressArr = newProgressArr;
  206. _this.playIndex = 0;
  207. $("#audio_new1").data("isplaying", false);
  208. window.hobyIsChanged = false; // 开始播放时,清除全局判断偏好设置是否修改
  209. _this.start_new();
  210. },
  211. // 5.退出朗读
  212. quitAudio_new: function () {
  213. var _this = this;
  214. window.lisFlag = "false";
  215. $('audio').each(function (index, item) {
  216. item.pause();
  217. item.src = "";
  218. });
  219. _this.readStartTime = 0;
  220. _this.currentPageReaddingCostTime = 0;
  221. _this.playIndex = 0;
  222. _this.runningIndex = 0;
  223. _this.initArr = [];
  224. window.localStorage.removeItem('isReading');
  225. $(".menu_hide").removeClass('menu_box');
  226. $("#audio_new1").data("isplaying", false);
  227. // _this.readType = 0
  228. // _this.isListening = false
  229. window.location.reload();
  230. },
  231. // 4 切换音频资源src
  232. changeAudioSource_new: function (e) {
  233. var _this = this;
  234. _this.pageMove(); // 修改页面卷取值
  235. _this.playIndex += 1;
  236. _this.runningIndex+=1;
  237. // TODO: 开始播放下一章,数据初始化
  238. console.log((_this.playIndex - 1) +'==='+ _this.progressArr.length);
  239. if ((_this.playIndex - 1) == _this.progressArr.length) {
  240. // 开启了自动播放
  241. window.autoPlayFlag = true;
  242. $('.read_nex_but').trigger("click");
  243. return;
  244. };
  245. var sibAudio = $(e.target).siblings('audio')[0];
  246. try {
  247. sibAudio.play();
  248. } catch (error) {
  249. alert("语音资源加载失败,请重试!");
  250. }
  251. window.playingAudioId = sibAudio.id; // 更新正在播放的audio的id
  252. $(e.target).attr({
  253. src: _this.setAudioSrc(_this.progressArr[_this.playIndex])
  254. });
  255. },
  256. // 3 设置audioSrc
  257. setAudioSrc: function (content) {
  258. var _this = this;
  259. var timestamp = (new Date()).getTime(); // 时间戳
  260. var id = this.generateUUID();
  261. var hoby = window.localStorage.getItem('listenHoby'); // 偏好设置
  262. var hobyObj = {};
  263. if (hoby) {
  264. hoby = JSON.parse(hoby);
  265. for (var key in hoby) {
  266. hobyObj[key] = hoby[key];
  267. }
  268. }
  269. return (_this.baseURL +
  270. "?" +
  271. "appkey=" + _this.appkey +
  272. "&timestamp=" + timestamp +
  273. "&sign=" + md5(_this.secretKey + timestamp) +
  274. "&id=" + id +
  275. "&sp=" + (hobyObj.sp || "1.0") +
  276. "&sr=" + (hobyObj.sr || 24000) +
  277. "&vol=" + (hobyObj.vol || "1.0") +
  278. "&tim=" + (hobyObj.tim || 0) +
  279. "&text=" + encodeURIComponent(content));
  280. },
  281. // 2 内容切块
  282. cutProgressNew: function (contentStr) {
  283. var _this = this;
  284. var progressArr = [];
  285. if (contentStr.length > 0) {
  286. var arrtemp = contentStr.split('<p>');
  287. arrtemp.forEach(function (item, index) {
  288. if (index != 0) {
  289. progressArr.push(item.replace('</p>', ''));
  290. }
  291. });
  292. };
  293. progressArr.splice(0, 1); // 去掉章节标题
  294. _this.pageProgressArr = progressArr;
  295. // 每段内容 不足80就加入数组,超出80的分段加入
  296. var tmpArr = [];
  297. progressArr.forEach(function(item , index){
  298. if(item.length <= 80){
  299. tmpArr.push(item);
  300. }else{
  301. var itemArr = item.split('');
  302. while(itemArr.length > 80){
  303. tmpArr.push(itemArr.splice(0,80).join(''));
  304. }
  305. tmpArr.push(itemArr.join(''));
  306. }
  307. });
  308. if(_this.isFirstCut){
  309. _this.initArr = tmpArr;
  310. _this.isFirstCut = false;
  311. }
  312. var tmpArr2 = [];
  313. tmpArr.forEach(function(item , index){
  314. if(/[\u4e00-\u9fff]/.test(item) || /[a-zA-Z]/i.test(item) || /\d/.test(item)){
  315. tmpArr2.push(item);
  316. }
  317. });
  318. _this.progressArr = tmpArr2;
  319. },
  320. bardown(e) {
  321. this.flags = true;
  322. var touch;
  323. if (e.touches) {
  324. touch = e.touches[0];
  325. } else {
  326. touch = e.target;
  327. }
  328. this.position.x = touch.offsetLeft;
  329. this.dx = touch.offsetLeft;
  330. },
  331. barmove(e) {
  332. if (this.flags) {
  333. var touch;
  334. if (e.touches) {
  335. touch = e.touches[0];
  336. } else {
  337. touch = e.target;
  338. }
  339. var base = audio_speed_bar.offsetLeft;
  340. var ebase = touch.clientX;
  341. var max = audio_speed_bar.offsetWidth - e.target.offsetWidth;
  342. var current;
  343. if (ebase - base > max) {
  344. current = max;
  345. } else if (ebase - base < 0) {
  346. current = 0;
  347. } else {
  348. current = ebase - base;
  349. }
  350. speed_bar_dot.style.left = current + "px";
  351. // 求比例值
  352. this.newSpeed = (current * 1.5 / max ).toFixed(2) - 0; // + 0.5
  353. }
  354. },
  355. barend(e) {
  356. this.flags = false;
  357. var current = this.newSpeed;
  358. console.log(current);
  359. if(current >= 0 && current < 0.19){
  360. this.newSpeed = 0.5;
  361. speed_bar_dot.style.left = "0%";
  362. }else if(current >= 0.19 && current < 0.56){
  363. this.newSpeed = 0.75;
  364. speed_bar_dot.style.left = "23%";
  365. }else if(current >= 0.56 && current < 0.94){
  366. this.newSpeed = 1.0;
  367. speed_bar_dot.style.left = "48%";
  368. }else if(current >= 0.94 && current < 1.3){
  369. this.newSpeed = 1.25;
  370. speed_bar_dot.style.left = "73%";
  371. }else if(current >= 1.3 && current <= 1.5){
  372. this.newSpeed = 1.5;
  373. speed_bar_dot.style.left = "96%";
  374. }
  375. this.ctrlSpeed(this.newSpeed);
  376. },
  377. ctrlSpeed(newSpeed) {
  378. var _this = this;
  379. _this.newSpeed = newSpeed;
  380. window.newSpeed = newSpeed;
  381. _this.updateUserHoby({ sp: newSpeed });
  382. },
  383. ctrlSpeed_dot(sp , left){
  384. speed_bar_dot.style.left = left;
  385. this.ctrlSpeed(sp);
  386. },
  387. voiceChoice(newVoiceCode) {
  388. var _this = this;
  389. _this.newVoiceCode = newVoiceCode;
  390. window.newVoiceCode = newVoiceCode;
  391. _this.updateUserHoby({ tim: newVoiceCode });
  392. },
  393. setTimeOut(minit) {
  394. var _this = this;
  395. window.localStorage.setItem('timeout', minit);
  396. window.clearTimeout(_this.timeId);
  397. _this.activeTime = minit;
  398. window.localStorage.setItem('startTime' , (new Date()).getTime());
  399. if (minit == '0') {
  400. _this.clearTimeOut();
  401. return;
  402. }
  403. minit = minit * 60 * 1000;
  404. _this.timeId = window.setTimeout(function () {
  405. _this.quitAudio_new();
  406. // _this.audioSrc = ""
  407. // _this.abortMission();
  408. // _this.clearAll();
  409. }, minit);
  410. },
  411. clearTimeOut() {
  412. var _this = this;
  413. window.clearTimeout(_this.timeout);
  414. },
  415. updateUserHoby(newHoby) {
  416. var _this = this;
  417. var hoby = window.localStorage.getItem('listenHoby');
  418. hoby = hoby ? JSON.parse(hoby) : {};
  419. for (var key in newHoby) {
  420. hoby[key] = newHoby[key];
  421. }
  422. window.localStorage.setItem('listenHoby', JSON.stringify(hoby));
  423. window.localStorage.setItem('timeout', _this.activeTime);
  424. },
  425. // new end
  426. listenNextPart() {
  427. var _this = this;
  428. _this.blog = "下一章的文章内容";
  429. _this.base64ResultArr = [];
  430. _this.initBlogContent();
  431. },
  432. // 突发首次请求
  433. suddenRequest: function () {
  434. var _this = this;
  435. _this.isLoadding = true;
  436. _this.startFlag = true;
  437. _this.isListening = false;
  438. _this.base64ResultArr = [];
  439. _this.progressArr = _this.progressArr.slice(_this.lisProIndex);
  440. _this.lisProIndex = 0;
  441. _this.linsteningProIndex = 0;
  442. _this.audioSrc = "";
  443. _this.$forceUpdate();
  444. _this.initBlogContent();
  445. },
  446. startListen() {
  447. var _this = this;
  448. // 修改阅读状态
  449. if (_this.readType == 1) return;
  450. _this.blog = res;
  451. _this.readType = 1;
  452. _this.isListening = false;
  453. // _this.suddenRequest()
  454. // new start
  455. _this.cutProgressNew(res);
  456. if (typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") {
  457. _this.start_new();
  458. }else{
  459. //監聽客户端抛出事件"WeixinJSBridgeReady"
  460. if (document.addEventListener) {
  461. document.addEventListener("WeixinJSBridgeReady", function(){
  462. _this.start_new();
  463. }, false);
  464. } else if (document.attachEvent) {
  465. document.attachEvent("WeixinJSBridgeReady", function(){
  466. _this.start_new();
  467. });
  468. document.attachEvent("onWeixinJSBridgeReady", function(){
  469. _this.start_new();
  470. });
  471. }
  472. }
  473. // new end
  474. if (startTime == 0) {
  475. _this.setTimeOut(_this.activeTime); //48 6635
  476. _this.readStartTime = (new Date()).getTime() - 0;
  477. window.localStorage.setItem('startTime', _this.readStartTime);
  478. } else {
  479. // 如果开始听书是上一张自动读下来的,就另开一个定时器,为更新定时器时间
  480. var leftTime = (new Date()).getTime() - startTime;
  481. var total = (window.localStorage.getItem('timeout') - 0) * 1000 * 60;
  482. if(total == 0){
  483. return;
  484. }
  485. var timeout = total - leftTime;
  486. console.log('总时差'+total);
  487. console.log('剩余时差'+timeout);
  488. _this.timeId = window.setTimeout(function () {
  489. _this.quitAudio_new();
  490. }, timeout);
  491. }
  492. // 增加localStorage中isReading状态值为自动听书加标志
  493. window.localStorage.setItem('isReading', 'true');
  494. },
  495. // var hobyIsChange = (_this.newVoiceCode != _this.activeSoundCode || _this.speed != _this.newSpeed)
  496. // // 有做修改的就重新请求
  497. // if (hobyIsChange) { // _this.isListening &&
  498. // _this.activeSoundCode = _this.newVoiceCode
  499. // _this.speed = _this.newSpeed
  500. // _this.abortMission()
  501. // _this.suddenRequest()
  502. // } else {
  503. // // 没有资源加载时可以切换播放状态
  504. // _this.isListening = !_this.isListening
  505. // }
  506. // $(".menu_hide").addClass('menu_box');
  507. // return false//"audioWorking"
  508. // } else {
  509. // return true //"notAudioWorking"
  510. // }
  511. quitAudio() {
  512. var _this = this;
  513. _this.clearAll();
  514. _this.$refs.audio.src = "";
  515. _this.base64ResultArr = [];
  516. _this.readType = 0;
  517. _this.isListening = false;
  518. _this.readStartTime = 0;
  519. _this.readNext = 0;
  520. _this.currentPageReaddingCostTime = 0;
  521. _this.abortMission();
  522. window.localStorage.setItem('isReading', 'false');
  523. },
  524. cutProgress(contentStr) {
  525. var _this = this;
  526. var progressArr = [];
  527. if (contentStr.length > 0) {
  528. var arrtemp = contentStr.split('<p>');
  529. arrtemp.forEach(function (item, index) {
  530. if (index != 0) {
  531. progressArr.push({
  532. index: index - 1,
  533. content: item.replace('</p>', '')
  534. });
  535. }
  536. });
  537. _this.progressArr = progressArr;
  538. return 0;
  539. } else {
  540. return 1;
  541. }
  542. },
  543. initBlogContent() {
  544. var _this = this;
  545. // 初始化阅读状态
  546. _this.clearAll();
  547. // 获取资源,中途修改偏好设置不用重新处理数据, 从之前的数组中截取然后请求
  548. if (_this.progressArr.length == 0) { //如果是整章从头处理
  549. if (_this.cutProgress(_this.blog)) return;
  550. _this.progressArr.forEach((function (item, index) {
  551. _this.string2audio(item.content, item.index);
  552. }));
  553. }
  554. _this.progressArr.forEach(function (item, index) {
  555. if (index == _this.linsteningProIndex) {
  556. item.blogArr.forEach(function (itemInner, indexInner) {
  557. // 请求JD语音接口
  558. _this.audioAjax(itemInner, indexInner, index);
  559. });
  560. }
  561. });
  562. },
  563. clearAll() {
  564. var _this = this;
  565. _this.abortMissionsArr = [];
  566. },
  567. string2audio(content, index) {
  568. var _this = this;
  569. // 拆分数组
  570. _this.progressArr[index].blogArr = _this.getContentParts(content);
  571. },
  572. getContentParts(content) {
  573. var contentArr = content.split('');
  574. var arr = [];
  575. var flag = true;
  576. var len = 80; // 掐段递增单位
  577. var maxLen = 200; // 最大的字符个数
  578. while (flag) {
  579. if (contentArr.length >= maxLen) {
  580. arr.push(contentArr.splice(0, len).join(''));
  581. len = len * 2 > maxLen ? maxLen : len * 2;
  582. } else {
  583. arr.push(contentArr.join(''));
  584. flag = false;
  585. }
  586. }
  587. return arr;
  588. },
  589. audioAjax(contentData, index, progressIndex) {
  590. var _this = this;
  591. // 准备数据
  592. _this.timeStamp = (new Date()).getTime(); // 本次请求的时间戳
  593. var timeStampCurrentNow = _this.timeStamp; // 局部变量在响应时做记录
  594. var index = index; // 字符串的索引
  595. _this.req.url = `${_this.baseURL}/?appkey=${this.appkey}&timestamp=${this.timeStamp}&sign=${md5(this.secretKey + this.timeStamp)}`;
  596. _this.req.headers['Request-Id'] = _this.generateUUID();
  597. // 获取用户偏好设置
  598. var hoby = window.localStorage.getItem('listenHoby');
  599. if (hoby) {
  600. hoby = JSON.parse(hoby);
  601. for (var key in hoby) {
  602. _this.headPro.parameters[key] = hoby[key];
  603. }
  604. }
  605. _this.req.headers['Property'] = JSON.stringify(_this.headPro);
  606. var req = {
  607. // 需要语音话的字符串
  608. data: { "": contentData },
  609. // data:contentData,
  610. // 放弃请求配置
  611. cancelToken: new axios.CancelToken(function executor(c) {
  612. _this.abortMissionsArr.push(c);
  613. })
  614. };
  615. for (var key in _this.req) {
  616. req[key] = _this.req[key];
  617. }
  618. // 发送请求
  619. _this
  620. // .axios(req)
  621. .axios({
  622. method: 'GET',
  623. url: "http://mp.ziread.cn/api/jdtts/test/1"
  624. })
  625. .then((res) => {
  626. if (res.data.code == 10000 && res.data.result.status == 0) {
  627. // 存储数据
  628. // 二维数组
  629. if (!_this.base64ResultArr[progressIndex]) {
  630. _this.base64ResultArr[progressIndex] = [];
  631. }
  632. _this.base64ResultArr[progressIndex].push({
  633. index: index,
  634. timeStamp: timeStampCurrentNow,
  635. audioSrc: res.data.result.audio
  636. });
  637. // 如果是整章第一次加载,
  638. if (index == 0 && _this.startFlag) {
  639. _this.isLoadding = false; // 隐藏loadding效果
  640. _this.startFlag = false; // 首次阅读
  641. _this.base64ResultArr[0].forEach(function (item, index) {
  642. if (item.index == 0) {
  643. _this.audioSrc = item.audioSrc;
  644. _this.$refs.audio.src = "data:audio/mpeg;base64," + _this.audioSrc;
  645. _this.$refs.audio.play();
  646. }
  647. });
  648. }
  649. // 如果下载完成对应段落中音频内容数量和发起下载的段落内容数量相同, 则发起下章节的请求
  650. if (_this.base64ResultArr[progressIndex].length == _this.progressArr[progressIndex].blogArr.length) {
  651. _this.linsteningProIndex += 1;
  652. }
  653. } else {
  654. alert("ERROR:CODE" + res.data.code);
  655. }
  656. })
  657. .catch((err) => {
  658. alert("请求语音失败,请联系客服");
  659. });
  660. },
  661. changeAudioSource(e) {
  662. var _this = this;
  663. var audioTag = e.target;
  664. var ProIndex = _this.lisProIndex;
  665. var innerIndex = _this.lisInnerIndex;
  666. // 下一个播放的真实索引
  667. var nextAudioIndex = innerIndex + 1;
  668. // 当前段落读完了
  669. if (_this.base64ResultArr[ProIndex] && (nextAudioIndex == _this.base64ResultArr[ProIndex].length)) {
  670. console.log("当前段落听书完毕,开启下一段落,索引:");
  671. _this.lisProIndex += 1;
  672. console.log(_this.lisProIndex);
  673. // 如果所有段落听书结束,开启翻页
  674. if (_this.lisProIndex == _this.base64ResultArr.length) {
  675. console.log("本章读完,开启下一章---TODO");
  676. // 触发加载下一章事件
  677. $('.read_main_other_box .read_nex_but').click();
  678. return;
  679. }
  680. // 替换音频资源
  681. _this.lisInnerIndex = 0;
  682. _this.audioSrc = _this.base64ResultArr[_this.lisProIndex][0].audioSrc;
  683. } else {
  684. // 有后续资源
  685. // if (!_this.base64ResultArr[_this.lisProIndex]) return
  686. _this.base64ResultArr[_this.lisProIndex].forEach(function (item, index) {
  687. if (item.index == nextAudioIndex) {
  688. _this.lisInnerIndex = nextAudioIndex;
  689. _this.audioSrc = item.audioSrc;
  690. }
  691. });
  692. }
  693. },
  694. abortMission() {
  695. console.log("done");
  696. if (this.abortMissionsArr.length == 0) return;
  697. this.abortMissionsArr.forEach(function (abFn) {
  698. abFn();
  699. });
  700. },
  701. },
  702. watch: {
  703. // 下载进度监听
  704. linsteningProIndex: function () {
  705. var _this = this;
  706. console.log("开始下载" + _this.linsteningProIndex + "章节");
  707. _this.initBlogContent();
  708. },
  709. },
  710. mounted: function () {
  711. var _this = this;
  712. // 获取用户偏好设置
  713. var hoby = window.localStorage.getItem('listenHoby') || '{"sp":"1.0","tim":"1"}';
  714. window.localStorage.setItem('listenHoby', hoby);
  715. var timeout = window.localStorage.getItem('timeout');
  716. if (hoby) {
  717. hoby = JSON.parse(hoby);
  718. _this.speed = hoby.sp ? hoby.sp - 0 : 1.0;
  719. _this.activeSoundCode = hoby.tim ? hoby.tim : '1'; // 当前使用的音色
  720. // 用户修改音色,给最新音色赋值, 全局点击文章内容时校验 最新 最初值是否相同, 如果相同则不重新请求
  721. _this.newSpeed = _this.speed;
  722. window.newSpeed = _this.speed;
  723. window.oldSpeed = _this.speed;
  724. _this.newVoiceCode = _this.activeSoundCode;
  725. window.newVoiceCode = _this.activeSoundCode;// 全局最新音色
  726. window.oldVoiceCode = _this.activeSoundCode;// 全局最初音色
  727. // 设置语速球位置
  728. var percent = '50%';
  729. if(_this.speed == 0.5){
  730. percent = '0%';
  731. }else if(_this.speed == 0.75){
  732. percent = '23%';
  733. }else if(_this.speed == 1.0){
  734. percent = '48%';
  735. }else if(_this.speed == 1.25){
  736. percent = '73%';
  737. }else if(_this.speed == 1.5){
  738. percent = '96%';
  739. }
  740. // var dot = _this.$refs.speed_dot
  741. var dot = $("#speed_bar_dot")[0];
  742. dot.style.left = percent;
  743. }
  744. if (timeout) {
  745. _this.activeTime = timeout;
  746. } else {
  747. _this.activeTime = 0;
  748. }
  749. this.isIOS = !!(navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)); //ios终端
  750. // 首次读书
  751. _this.startListen();
  752. // 网络检测
  753. _this.scanNetConnect();
  754. }
  755. });
  756. }