jQuery.speech.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. Create By AZ
  3. Date: 2016-01-11
  4. blog: http://www.tuterm.com
  5. 可以任意使用,保留作者信息以溯源
  6. */
  7. ;
  8. (function($) {
  9. $.fn.speech = function(options) {
  10. var defaults = {
  11. "speech": true, //通过点击链接播报,还是直接播报
  12. "lang": "zh", //语言
  13. "speed": 3, //语速
  14. "sWidth": 16, //链接按钮的宽度
  15. "sHeight": 13, //链接按钮的高度
  16. "https": true, //启用https
  17. "bg": "./image/speech.png", //链接按钮的背景图片
  18. "content": "这是一段测试内容" //直接播报内容
  19. };
  20. var options = $.extend(defaults, options);
  21. return this.each(function() {
  22. var _this = $(this),
  23. _iframe = _this.find(".speech_iframe"),
  24. http = options.https ? "https" : "http",
  25. content = _this.text();
  26. content = (!content || content === undefined || content === null) ? options.content : content;
  27. var src = http + '://tts.baidu.com/text2audio?lan=' + options.lang + '&ie=UTF-8&text=' + content + '&spd=' + options.speed;
  28. if (options.speech) {
  29. //点击链接播报
  30. var sClick = "<a href='javascript:void(0);' class='speech'></a>";
  31. _this.append(sClick);
  32. var _speech = _this.find(".speech");
  33. _speech.css({ //设置链接样式
  34. "width": options.sWidth,
  35. "height": options.sHeight,
  36. "display": "inline-block",
  37. "background": "url(" + options.bg + ") no-repeat"
  38. });
  39. _speech.on('click', function() { //捕获点击事件
  40. _iframe.length > 0 ? _iframe.attr("src", src) : (function() {
  41. var iframe = "<iframe height='0' width='0' class='speech_iframe' scrolling='no' frameborder='0' src='" + src + "' ></iframe>";
  42. _this.append(iframe);
  43. })();
  44. });
  45. } else { //自动播报
  46. _iframe.length > 0 ? _iframe.attr("src", src) : (function() {
  47. var iframe = "<iframe height='0' width='0' class='speech_iframe' scrolling='no' frameborder='0' src='" + src + "' ></iframe>";
  48. _this.append(iframe);
  49. })();
  50. }
  51. });
  52. };
  53. })(jQuery);