Logic Machine Forum
sound - Printable Version

+- Logic Machine Forum (https://forum.logicmachine.net)
+-- Forum: LogicMachine eco-system (https://forum.logicmachine.net/forumdisplay.php?fid=1)
+--- Forum: Scripting (https://forum.logicmachine.net/forumdisplay.php?fid=8)
+--- Thread: sound (/showthread.php?tid=2541)



sound - balatis - 25.03.2020

Hi 
i try to use below skript for play a sound when i have an alarm , but does not work in alerts i have this message "default page does not excists exit HTMLcreation" no erros ,no logs...
thanks in advance

  1. -- * Audio Alarm Notification Module Version 1.4 Created by Erwin van der Zwart * --
  2. -- * This script perform automaticly all needed actions to support audio alerts * --
  3. --  After running script once refresh browser and write value to object for audio --
  4. -- ******************************** SET PARAMETERS ****************************** --
  5.  
  6. -- Group address to trigger the alarm notification
  7. Audio_Trigger_Group_Address = '1/1/1' -- !! MUST BE A BIT OBJECT !!
  8.  
  9. -- Audio on value 0 and value 1 or on value 1 only
  10. Audio_on_value_1_only = true -- Set to true for audio on value 1 only
  11.  
  12. -- Stop audio on value 0 (used only when Audio_on_value_1_only = true)
  13. Stop_on_value_0 = true -- Set to false to play complete audio file when receiving value 0
  14.  
  15. -- Repeat audio until value is 0 (used only when Audio_on_value_1_only = true and Stop_on_value_0 = true)
  16. Repeat_on_value_1 = true -- Set to true for audio loop until object value is false
  17.  
  18. -- Check object value on load of visu to start direct based on object value
  19. Start_On_Load = true -- Set to true for audio on load based on object value
  20.  
  21. -- Set interval (in seconds) for audio repeat playing file until mute is pressed (used only when Audio_on_value_1_only = true and Stop_on_value_0 = true)
  22. Audio_Play_Interval_Time = 10 -- Adjust to length of playing file
  23.  
  24. -- URL to use for downloading a audiofile to the controller on value 0 (only used / needed when line 8 is set to false)
  25. URL_Audio_File_0 = 'http://https://www.computerhope.com/jargon/m/example.mp3'
  26.  
  27. -- URL to use for downloading a audiofile to the controller on value 1
  28. URL_Audio_File_1 = 'https://www.computerhope.com/jargon/m/example.mp3'
  29.  
  30. -- !IMPORTANT! internet must be available for the controller to download a file
  31. -- check DNS and default gateway or copy your own audio files to the img / backgrounds
  32. -- folder and name it 'alarm_0.xxx' (format like line 13) and 'alarm_1.xxx' (format like line 13)
  33.  
  34. -- Downloaded audio file formaton on value 0 (only used / needed when line 8 is set to false)
  35. Audio_File_Format_0 = 'mp3'
  36.  
  37. -- Downloaded audio file formaton on value 1
  38. Audio_File_Format_1 = 'mp3'
  39.  
  40. -- Create automaticly iframe with logout.html on startpage
  41. Create_Automatic = true -- Set to false to disable auto create and run script once
  42.  
  43. -- Delete HTML alarm function from controller
  44. Delete_HTML = false -- Set to true to delete this function and run script once
  45.  
  46. -- ******************************** END PARAMETERS ****************************** --
  47. -- ********************* DON'T CHANGE ANYTHING UNDER THIS LINE ****************** --
  48.  
  49. -- Set interval (in seconds) for audio repeat playing file until mute is pressed to milliseconds
  50. Audio_Play_Interval_Time = Audio_Play_Interval_Time * 1000
  51. if Audio_Play_Interval_Time < 1000 then
  52.   Audio_Play_Interval_Time = 1000
  53. end
  54.  
  55. -- Create HTML content
  56. page = [[
  57. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  58. <html xmlns="http://www.w3.org/1999/xhtml">
  59. <head>
  60. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  61. <title>homeLYnk Alarm Notifications</title>
  62. <style type="text/css">
  63. body {
  64. background-color: transparent;
  65. }
  66. </style>
  67. </head>
  68. <body>
  69. <script type="text/javascript">
  70. // ***** Make link to parent from iframe *****
  71. var p = window.parent, root, addr;
  72. var ip = location.host;
  73. var URL = "http://" + ip + "/scada/resources/img/";
  74.  
  75. if (p && p.objectStore) {
  76. ]]
  77. if Audio_on_value_1_only == false then
  78. page = page .. [[
  79. // Create snd for playing audio
  80. var snd_0 = new Audio(URL + "alarm_0.]] .. Audio_File_Format_0 .. [[");
  81. var snd_1 = new Audio(URL + "alarm_1.]] .. Audio_File_Format_1 .. [[");
  82. ]]
  83. else
  84. page = page .. [[
  85. // Create snd for playing audio
  86. var snd_1 = new Audio(URL + "alarm_1.]] .. Audio_File_Format_1 .. [[");
  87. // Create alertaudio for loop playing audio
  88. var alertaudio = ""
  89.  
  90. function playalert_loop() {
  91. if (snd_1.paused || snd_1.ended || snd_1.currentTime == 0 ) {
  92.     snd_1.play();
  93. }
  94. }
  95.  
  96. function playalert() {
  97. // Create loop
  98. if(alertaudio==""){
  99.     alertaudio = window.setInterval("playalert_loop()",]] .. Audio_Play_Interval_Time .. [[);
  100.   }
  101. // Start loop direct
  102. playalert_loop();
  103. }
  104.  
  105. function stopalert() {
  106. if(alertaudio!=""){
  107. window.clearInterval(alertaudio)
  108.     alertaudio=""
  109. }
  110. if (!snd_1.paused || !snd_1.ended || snd_1.currentTime > 0 ) {
  111.     snd_1.pause();
  112. snd_1.currentTime = 0;
  113. }

  114. ]] 
  115. end
  116. page = page ..  [[
  117. /* ********** DON'T CHANGE ANYTHING ABOVE THIS LINE ******* */
  118. /* ********** HTML FILE FOR HOMELYNK AUDIO MESSAGES  ******* */
  119. /* ************** CREATED BY ERWIN VAN DER ZWART ********** */
  120. /* ******************************************************** */   
  121. /*  TO ADD COPY BLOCK(S) AND CHANGE (2x) addr0 to addr(x)  */
  122. /* ******************************************************** */
  123.  
  124.   /* START BLOCK */
  125. /* ]] .. Audio_Trigger_Group_Address .. [[ = ALARM TRIGGER ADDRES */
  126. addr0 = p.Scada.encodeGroupAddress(']] .. Audio_Trigger_Group_Address .. [[');   
  127. p.objectStore.addListener(addr0, function(obj, type) {
  128.  
  129. /* to avoid play on opening page */
  130.     if (type == 'init') {]]
  131. if Start_On_Load == false then
  132. page = page .. [[
  133.     return;
  134.   ]]
  135. end
  136. page = page .. [[
  137.     }
  138. ]]
  139. if Audio_on_value_1_only == false then
  140. page = page .. [[    
  141.  
  142.   if ( obj.value == 0 ) {
  143.   if (!snd_0.paused || !snd_0.ended || snd_0.currentTime > 0 ) {
  144.     snd_0.pause();
  145. snd_0.currentTime = 0;
  146. }
  147.     if (!snd_1.paused || !snd_1.ended || snd_1.currentTime > 0 ) {
  148.     snd_1.pause();
  149. snd_1.currentTime = 0;
  150. }
  151. snd_0.play();
  152.   }
  153.  
  154.   if ( obj.value == 1 ) {
  155. if (!snd_0.paused || !snd_0.ended || snd_0.currentTime > 0 ) {
  156.     snd_0.pause();
  157. snd_0.currentTime = 0;
  158. }
  159.     if (!snd_1.paused || !snd_1.ended || snd_1.currentTime > 0 ) {
  160.     snd_1.pause();
  161. snd_1.currentTime = 0;
  162. }
  163.   snd_1.play();
  164. }
  165. ]]
  166. else
  167.   if Stop_on_value_0 == true then
  168.     if Repeat_on_value_1 == true then
  169.     page = page .. [[
  170.  
  171.   if ( obj.value == 0 ) {
  172.     stopalert();
  173.   }
  174.  
  175.   if ( obj.value == 1 ) {
  176.   playalert();
  177. }
  178. ]] 
  179.   else
  180. page = page .. [[
  181.  
  182.     if ( obj.value == 0 ) {
  183.     if (!snd_1.paused || !snd_1.ended || snd_1.currentTime > 0 ) {
  184.     snd_1.pause();
  185. snd_1.currentTime = 0;
  186. }
  187.   }
  188.  
  189.   if ( obj.value == 1 ) {
  190.   if (!snd_1.paused || !snd_1.ended || snd_1.currentTime > 0 ) {
  191.     snd_1.pause();
  192. snd_1.currentTime = 0;
  193. }
  194. snd_1.play();
  195. }
  196. ]] 
  197.   end
  198.   else
  199.     page = page .. [[
  200.  
  201.     if ( obj.value == 0 ) {
  202.  
  203.   }
  204.  
  205.   if ( obj.value == 1 ) {
  206.   if (!snd_1.paused || !snd_1.ended || snd_1.currentTime > 0 ) {
  207.     snd_1.pause();
  208. snd_1.currentTime = 0;
  209. }
  210. snd_1.play();
  211. }
  212. ]] 
  213.   end
  214. end
  215. page = page ..  [[
  216.   });
  217. /* END OF ]] .. Audio_Trigger_Group_Address .. [[ */
  218.  
  219. /* ******************************************************** */
  220.  
  221. /* ******************************************************** */   
  222. /*  TO ADD COPY BLOCK(S) AND CHANGE (2x) addr0 to addr(x)  */
  223. /* ******************************************************** */
  224.  
  225. // ADD HERE EXTRA BLOCKS IF NEEDED
  226.  
  227. /* ******************************************************** */
  228.  
  229. /* ********** DON'T CHANGE ANYTHING BELOW THIS LINE ******* */
  230.  
  231. }
  232. </script>
  233. </div>
  234. </body>
  235. </html>
  236. ]]
  237.  
  238. -- Write HTML file to controller
  239. io.writefile("/www/scada/resources/img/alarm.html", page)
  240.  
  241. -- use this as frame URL -> /scada/resources/img/alarm.html
  242.  
  243. -- Check if html must be automaticly created inside iframe with alarm.html on startpage
  244. if Create_Automatic == true then
  245.  
  246.   -- Get default startpage
  247.   query = 'SELECT id, usermode_param FROM visfloors'
  248. for _, floor in ipairs(db:getall(query)) do
  249. if floor.usermode_param == "D" then
  250.     default_startpage = floor.id
  251. end
  252. end
  253.  
  254.   -- Check if default page excists else exit script
  255.   if default_startpage == nil then
  256.     alert("Default page does not excists, exit HTML creation")
  257.     --Exit script
  258.     return
  259.   end
  260.  
  261.   -- Check if object already exist
  262.   object_exists = false
  263.   query = 'SELECT floor, type, name, params FROM visobjects'
  264.   for _, visobject in ipairs(db:getall(query)) do
  265.     if visobject.floor == default_startpage and (visobject.type == 9 or visobject.type == "9") and visobject.name == "alarm" then
  266.       object_exists = true   
  267.     end
  268. end
  269.  
  270.   -- Create if object doesn't exist
  271.   if object_exists == false then
  272.   db:insert('visobjects', {floor = default_startpage, type = 9, params = '{"source":"url","url":"/scada/resources/img/alarm.html","width":50,"height":50}', locx = 0 , locy = 0, name = "alarm", notouch = 1, nobg = 1,})
  273.   end
  274.  
  275.   if Audio_on_value_1_only == false then
  276.   -- Download alarm file on value 0 to controler local
  277.     os.execute('wget -q -U Mozilla -O /www/scada/resources/img/alarm_0.' .. Audio_File_Format_0 .. ' ' ..  URL_Audio_File_0)
  278.     -- Download alarm file on value 1 to controler local
  279.   os.execute('wget -q -U Mozilla -O /www/scada/resources/img/alarm_1.' .. Audio_File_Format_1 .. ' ' ..  URL_Audio_File_1)
  280.   else
  281.     -- Download alarm file on value 1 to controler local
  282.   os.execute('wget -q -U Mozilla -O /www/scada/resources/img/alarm_1.' .. Audio_File_Format_1 .. ' ' ..  URL_Audio_File_1)
  283.   end
  284. end
  285.  
  286. log ("Audio alerts are added")
  287.  
  288. -- Check if HTML logout function must be deleted from the controller
  289. if Delete_HTML == true then
  290.  
  291.   -- Get default startpage
  292.   query = 'SELECT id, usermode_param FROM visfloors'
  293. for _, floor in ipairs(db:getall(query)) do
  294. if floor.usermode_param == "D" then
  295.     default_startpage = floor.id
  296. end
  297. end
  298.  
  299.   -- Check if default page excists else exit script
  300.   if default_startpage == nil then
  301.     alert("Default page does not excists, exit HTML deletion")
  302.     --Exit script
  303.     return
  304.   end
  305.  
  306.   -- Select all entrys from DB inside table 'visobjects'
  307.   query = 'SELECT id, floor, type, name, params FROM visobjects'
  308. for _, visobject in ipairs(db:getall(query)) do
  309.   if visobject.floor == default_startpage and (visobject.type == 9 or visobject.type == "9") and visobject.name == "alarm" then
  310.       current = visobject.id
  311.       db:delete('visobjects', { id = current })
  312.     end
  313.   end
  314.  
  315.   --Delete HTML file from HL dir
  316.   os.remove("/www/scada/resources/img/alarm.html")
  317.  
  318.   if Audio_on_value_1_only == false then
  319.   --Delete Audio file on value 0 from HL dir
  320.   os.remove("/www/scada/resources/img/alarm_0." .. Audio_File_Format_0)
  321.  
  322.     --Delete Audio file on value 1from HL dir
  323.   os.remove("/www/scada/resources/img/alarm_1." .. Audio_File_Format_1)
  324.   else
  325.     --Delete Audio file on value 1from HL dir
  326.   os.remove("/www/scada/resources/img/alarm_1." .. Audio_File_Format_1)
  327.   end
  328.   log ("Audio alerts are deleted")
  329. end
  330.  
  331. -- Disable script when done automaticly
  332. script.disable(_SCRIPTNAME)



RE: sound - admin - 25.03.2020

Make sure that you have a plan in Vis. structure with "Usermode visualization" parameter set to "Show, make default"


RE: sound - balatis - 26.03.2020

(25.03.2020, 13:15)admin Wrote: Make sure that you have a plan in Vis. structure with "Usermode visualization" parameter set to "Show, make default"
Thanks Admin!


RE: sound - Domoticatorino - 21.08.2020

Hi Balatis,
file sounds till you make the acknowledge?

I have to create an alarm system for a reception desk. I would like to use an android touch.
What do you suggest? Thanks.


RE: sound - Erwin van der Zwart - 23.08.2020

Hi,

This is a very old script and was used before we had custom JS.

Due the implemantation of custom JS we had better options to implement things..

Use this custom JS instead of the old script above:
Code:
// Closing current script section to add elements
</script>
<audio id="SE_Audio" style="display: none;"></audio>
<script type="text/javascript"> // Starting new script section after adding elements 

$(function(){

   // Table with parameters address, audio URL, repeat, interval in ms
   var AudioTable = [
     { address:"32/0/0", url:"/user/beep.mp3", repeat:true, interval: 2000, intervalHandle: 0},
     { address:"32/0/1", url:"/user/beep1.mp3", repeat:true, interval: 2000, intervalHandle: 0},
     { address:"32/0/2", url:"/user/beep.mp3", repeat:false, interval: 2000, intervalHandle: 0},
     { address:"32/0/3", url:"/user/beep1.mp3", repeat:false, interval: 2000, intervalHandle: 0},
   ];
        
   var ctx = new(window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.oAudioContext || window.msAudioContext), request = new XMLHttpRequest();
   var snd = document.getElementById("SE_Audio");
 
  function getMobileOperatingSystem() {
    var userAgent = navigator.userAgent || navigator.vendor || window.opera;
    //console.log(userAgent)
    if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
      return 'iOS';
    } else if ( userAgent.match(/Android/i)) {
      return 'Android';
    } else if ( userAgent.match(/iKonWebTouch/i)) {
      return 'U.Motion';
    } else {
      return 'PC';
    }
  }

  var OS_Version = getMobileOperatingSystem();
 
  // Fix iOS Audio Context
  (function() {
    var fixAudioContext = function (e) {
      if (ctx) {
        // Create empty buffer
        var buffer = ctx.createBuffer(1, 1, 22050);
        var source = ctx.createBufferSource();
        source.buffer = buffer;
        // Connect to output
        source.connect(ctx.destination);
        // Play sound
        if (source.start) {
          source.start(0);
        } else if (source.play) {
          source.play(0);
        } else if (source.noteOn) {
          source.noteOn(0);
        }
      }
      // Check if document is loaded in iframe
      if (window.frameElement){
        // Remove event listeners from parent
        var thisparent = window.parent;
        thisparent.document.removeEventListener('touchstart', fixAudioContext);
        thisparent.document.removeEventListener('touchend', fixAudioContext);
      }
      // Remove events
      document.removeEventListener('touchstart', fixAudioContext);
      document.removeEventListener('touchend', fixAudioContext);
    };
    // Check if document is loaded in iframe
    if (window.frameElement){
      // Add event listeners to parent
      var thisparent = window.parent;
      // Event listener for iOS 6-8 (was previous touchstart event)
      thisparent.document.addEventListener('touchstart', fixAudioContext);
      // Event listener for iOS 9+ (is now touchend event)
      thisparent.document.addEventListener('touchend', fixAudioContext);
    }
    // Event listener for iOS 6-8 (was previous touchstart event)
    document.addEventListener('touchstart', fixAudioContext);
    // Event listener for iOS 9+ (is now touchend event)
    document.addEventListener('touchend', fixAudioContext);
  })();
 
  // Function to play audio by URL
  function Play_Audio(url){
    //console.log(OS_Version)
    if (OS_Version === 'Android' || OS_Version === 'U.Motion' ){
        //alert(OS_Version);
      snd.src = url;
        snd.pause();
        sndcurrentTime = 0;
      //snd.load();
      snd.play();
    } else {
      request.open("GET", url, true);
      request.responseType = "arraybuffer";
      request.onload = function(){
          ctx.decodeAudioData(request.response, onDecoded);
      }
      function onDecoded(buffer){
          var bufferSource = ctx.createBufferSource();
          bufferSource.buffer = buffer;
          bufferSource.connect(ctx.destination);
          bufferSource.start();
      }
      request.send();
    }
  };
 
  // Function to create event listeners
  function CreateListeners(groupaddr, url, repeat, interval, item){
    // Make event listener to object
    if (typeof grp != 'undefined') {
      grp.listen(groupaddr, function(object, state) {
        var value = object.value;
        if (state == 'value') {
          if (value == 1) {
            if (repeat == true){
              if (AudioTable[item].intervalHandle === null) {
                Play_Audio(url);
                  AudioTable[item].intervalHandle = setInterval(function() {
                                    Play_Audio(url);
                                }, interval);
              }
              } else {
                Play_Audio(url);
              }
          } else {
            if (AudioTable[item].intervalHandle !== null) {
                   clearInterval(AudioTable[item].intervalHandle);
                   AudioTable[item].intervalHandle = null;
               }
        }
        }
      }, true);
    }
    }
 
  // Start creating listeners
  for (var i in AudioTable) {
    CreateListeners(AudioTable[i].address, AudioTable[i].url, AudioTable[i].repeat, AudioTable[i].interval, i);
  }
 
});
BR,

Erwin


RE: sound - Domoticatorino - 23.08.2020

Thank you Erwin.