Archive for August, 2011

Play Sound in HTML5 and cross browser support with backward compatability.

In the last post in this series [ read here ] I added the clock timing logic to the HTML workout timer.

The next feature to add is round and interval audio. I want to ring a bell at the beginning and the end of each round, a warning before a change in work state, etc.

This is quite a bit more difficult than it sounds because we need to support both the differences between HTML5 implementation specifics in each of the modern browsers as well as  support still popular older browsers that only support pre “5″ versions of HTML.

I wanted code that would play an Audio file in the current versions of Internet Explorer, Firefox, Chrome, Opera and Safari on Windows, Firefox, Chrome, and Safari on the Mac and on old HTML 4 browsers. As it turns out some current browsers will play .wav but not .mp3 files. Some with play .mp3 but not .wav and some will play both.

So, I built a small test application that would play in all !

The UI was simple enough:

Lets look at the code and I’ll call out the notable points of interest.


<!DOCTYPE html>
<html>  
<head>
<title>Play Audio</title>
<script src="script/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="script/modernizr-latest.js" type="text/javascript"></script>
<script type="text/javascript">
    var currentFile = "";
    function playAudio() {

        var oAudio = document.getElementById('myaudio');
        // See if we already loaded this audio file.
        if ($("#audiofile").val() !== currentFile) {
            oAudio.src = $("#audiofile").val();
            currentFile = $("#audiofile").val();
        }
            var test = $("#myaudio");
            test.src = $("#audiofile").val();
        oAudio.play();   
    }
    
    $(function() {
        if (Modernizr.audio) {
            if (Modernizr.audio.wav) {
                $("#audiofile").val("sounds/sample.wav"); 
            }
            if (Modernizr.audio.mp3) {
                $("#audiofile").val("sounds/sample.mp3");
            }
        }
        else {
          $("#HTML5Audio").hide();
          $("#OldSound").html('<embed src="sounds/sample.wav" 
                                      autostart=false width=1 height=1 
                                      id="LegacySound" 
                                      enablejavascript="true" >');
        }

    });
</script>
</head>
  
<body>
  <div style="text-align: center;"> 
    <h1>Click to Play Sound<br /></h1>
    <div id="HTML5Audio">
    <input id="audiofile" type="text" value="" style="display: none;"/>
    <br />
  
    <button id="play" onclick="playAudio();">
        Play
    </button>
    </div>
    <audio id="myaudio">
        <script>
        function LegacyPlaySound(soundobj) {
          var thissound=document.getElementById(soundobj);
          thissound.Play();
        }
        </script>
        <span id="OldSound"></span>        
        <input type="button" value="Play Sound"  
               onClick="LegacyPlaySound('LegacySound')">
    </audio>

</div>

</body>
</html>

First, you will notice that I’ve included jQuery as I now do in all my web based UI and I’ve included Modernizr, which I’ll use to determine where the HTML5 audio tag is supported and if it is, what audio file format that I need to use for the browser that I happen to be running in.

I’ve created a “sounds” directory and sound files named “sample.wmv” and “sample.mp3″.

Note the declaration of an audio element on line 54. If the browser supports the HTML5 Audio element the code between lines 54 and 64 will be ignored. If the browser does not support HTML5 audio then that markup will be rendered (including the JavaScript). The actual LegacySound object that gets played on line 63 is only needed if the browser is not HTML5 and it will be created by some JavaScript when the page is loaded only if it is needed,

Lines 6 to 20 are a JavaScript function to play the HTML5 audio element. Note that I’ve used a technique to improve performance slightly if name of the audio file to be played has not changed since the last time the function was called.

Beginning on line 22 code will be executed when the document is ready (loaded).

Line 23 tests to see if the HTML Audio tag is supported.

Then we check to see which media file type is supported.

If the HTML5 Audio tag is not supported then line 32 hides the user interface elements that would be used with the HTML Audio and line 33 creates the embedded media object to be played by older browsers.

I’ve tested this code in all the browsers listed above as well as Netscape 7 for HTML 4 compatibility.

You can click [ HERE ] to download a working sample.

Weekly Links– 2010_31 (50 for Web Devs & Other Geeks)

Software Developer Links of the Week.
  1. Google has started working on a Chrome mechanism to let extensions download items from a Web page
  2. Windows Azure – Authenticate ASP.Net Azure Web Application using Google Credentials
  3. How open source is transforming the publishing industry
  4. 10 freeware to boost office productivity
  5. Are frameworks making developers dumb?
  6. Poll: What is the future of desktop app development?
  7. American IT workers file suit for jobs lost due to outsourcing
  8. How to Communicate between two Local Silverlight Applications?
  9. HTML5 WebWorkers Experiment
  10. Offline Gmail Desktop App Tutorial
  11. Configuring Flash Builder 4.5 for iOS Development
  12. How to Validate ASP.NET Web Forms Using a Business Rules Engine
  13. Consuming a Web Service .NET with VB6.0 App
  14. New HP TouchPad owners go get your free 50GB of lifetime cloud storage
  15. Deloitte: 4G could produce 771,000 new jobs in U.S. by 2016
  16. Skype Acquiring Startup GroupMe for Group Text Messaging
  17. Installing Linux on old PC’s
  18. Domain Name Suggests New Kindle Will Have Stylus
  19. Scott Guthrie to Lead Azure Application Platform Team
  20. Survey Reveals Shifting Cloud Attitudes
  21. Best practices to architect applications in the IBM Cloud
  22. 11 ways to get more traffic to your web site
  23. Silverlight Toolkit Samples Application
  24. Desktop Google Reader written with WPF
  25. Will Microsoft compensation changes help retain employees? We’ll find out soon Read the rest of this entry »

Building an HTML App – Workout Timer – Clock Logic

In [ this post ] I introduced an HTML application that I intended to build.

I’ve been picking away at the logic (though haven’t gotten to the HTMP “5″ stuff yet) and thought I’d share the milestone.

Note that the gray area in the screen shot below is not implemented yet.

Here are some of the features that ARE implemented.

  • Work and Rest mode count downs.
  • Start / Pause
  • Reset Time & Round Count
  • Title Bar Status Indicator
  • Local Time Indicator
  • Total elapsed time clock (not effected by paused time)
  • Accumulated Work Time
  • Accumulated Rest Time

A couple points of interest for newer JavaScript developers.

First, note the use of ENUM (ish) conscructs.

I can define an enum as follows:


var Mode = { "STOP": 0, "WORK": 1, "REST": 3, "HIGH": 4, "LOW": 5, "LOW": 6 };

And then use it this way:


var CurrentMode = Mode.REST;
....
 if (CurrentMode == Mode.REST) {
    ......
	}

Also, I can create a simple object like this. Note the object instance allocations after the definition :


function clock(h, m, s, ms) {
	this.hours = h;
	this.minutes = m;
	this.seconds = s;
	this.miliseconds = ms;
}

var workClock = new clock(0, 0, 0, 0);
var elapsedClock = new clock(0, 0, 0, 0);
var totalWorkClock = new clock(0, 0, 0, 0);
var totalRestClock = new clock(0, 0, 0, 0);

Then I can access Object Instance Properties like this:


workClock.minutes = RoundLengthMinutes;

The entire source listing is below.

You can run the page in it’s current form at http://www.misfitgeek.com/fighttimer/

Please report bugs and make feature suggestions using by submitting comments.

To view the source code click below.

Read the rest of this entry »

Weekly Links– 2010_30 (50 for Web Devs & Other Geeks)

Software Developer Links of the Week.
  1. IBM executive says PC era is in its twilight
  2. Better web font loading with JavaScript
  3. In JavaScript, curly brace placement matters: An example
  4. The pros and cons of developing a complete Javascript UI
  5. Toshiba Thrive Tablet
  6. Should Microsoft make a break with the past and drop legacy support?
  7. Apple’s EU legal win could prevent all OEMs from building tablets
  8. Kindle Cloud Reader: Amazon’s answer to Apple’s app restriction
  9. Safari Omnibar solves the search two-step
  10. Nintendo has good reason to not develop for iOS
  11. Google’s Motorola acquisition: Nail in the Android patent coffin?
  12. Firefox 6 available ahead of official launch
  13. Key Process Patterns
  14. Use jQuery.extend() and Ajax to “construct” your JavaScript Objects from Server Objects
  15. The Biggest Changes in C++11 (and Why You Should Care)
  16. Lessons from Amazon Cloud Lightning Strike Outage
  17. Getting Started With Android App Development: Eclipse and the Android SDK
  18. Generating Code Using Text Template Transformation Toolkit (T4)
  19. Windows Laptop Makers Can’t Catch Up to the MacBook Air
  20. 10 things you can do to improve your Web site right now
  21. Cloud Storage Studio
  22. Android Tablets Grab 20 Percent of Market Share
  23. Visual Studio Asynchronous Programming Videos
  24. 10 basic search engine optimization tips
  25. Engineer of original IBM PC declares end of PC era

    Read the rest of this entry »

Beginning an HTML5 Application – The Requirements

More and more developers are starting to think about building applications that have both on-line and off-line features using HTML5.

I’ve been giving this some thought and have decided to build one myself.

I thought for a while about what sort of application would make for a good showcase.

It’s one of the though things about building examples – no one tells you what your next application is supposed to do.

In any event, what I decided on is in interval training application for boxers. A “round timer”.

Since this is intended to be a learning application and there are some great designer types and jQuery developers that read my blog, I thought it would be cool to design and develop this application by committee.

Here are some of the features that I’m hoping will help make it a good showcase.

  • Lots of running logic implemented in JavaScript CSS and jQuery
  • Play audio videos for interval sounds.
  • Use Local Storage to save user specific profiles.

Once the basics are done I could expand the application with things like:

  • Server based back ups and workout suggestions.
  • Embedding Video Demonstrations for workouts.
  • Web Sockets for Peer to Peer – team workouts.

I want the user interface to be highly configurable. Here is a quick layout.

I’ll include the markup for the UI prototype for anyone that wants it but remember.

It’s JUST a UI prototype. It needs to be refactored for CSS, etc,

PLEASE post your suggestions about what form the application should take – both from a feature set perspective as well as from a technical one.

Click [ Read More ] to see markup …..

Read the rest of this entry »

ASP.NET Password Strength Indicator with jQuery Plugin.

Password strength is a key factor in account security for weeb applications. As developers we all have a basic understanding of what a secure password is but the averge consumer of internet applications doesn’t so adding a visual indicator when your user selectes a password is a great feature.

There are many, many plugins that we could select from to implement this feature I’ve selected this one which makes things very easy.

http://plugins.jquery.com/project/password_strength


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" 
    AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery.password_strength.js" type="text/javascript">
    </script>
    <style type="text/css"> 
    .password_strength {
	    }
    .password_strength_1 {
	    background-color: #fcb6b1;
	    }
    .password_strength_2 {
	    background-color: #fccab1;
	    }
    .password_strength_3 {
	    background-color: #fcfbb1;
	    }
    .password_strength_4 {
	    background-color: #dafcb1;
	    }
    .password_strength_5 {
	    background-color: #bcfcb1;
	    }
    </style> 
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>Password Strength</h2>

    <table style="border-spacing: 0px; border-style: none">
      <tbody>
      <tr>
        <td style="text-align: right"><label>User Name:</label></td>
        <td>
           <asp:TextBox ID="username" runat="server" Width="200px"></asp:TextBox>
        </td>
      </tr>
      <tr>
        <td style="text-align: right"><label>Password:</label></td>
        <td>
            <asp:TextBox ID="password" class=password runat="server" 
                ClientIDMode="Static" TextMode="Password" Width="200px">
            </asp:TextBox> 
        </td>
      </tr>
      </tbody>
    </table>

  
<script type="text/javascript">
    $('form').attr('autocomplete', 'off');
    $('#password').password_strength();
</script> 

</asp:Content>

In the code above I’ve used in-line CSS and script for the sake of learning simplicity.

The CSS is used by the plugin to set the color that corresponds with the “level” of the password as entered.

The script block starting on line 50 turns autocomplete off for the form (we’re working with a password after all) and applies the password strength functionality to the ASP.NET textbox controll names “password:.

As with all the ASP.NET jQuery work that we’ve been doing, we must set the Client Id Mode to “static” so tha tthe ASP.NET runtime does not modify the client ID of the emitted HTML text box.


You can download a working sample [ HERE]


Weekly Links– 2010_27 (50 for Web Devs & Other Geeks)

Software Developer Links of the Week.
  1. The Dangers of HTML5: WebSockets and Stable Standards
  2. The Complete Datagrid (Alphabetic and Customized Paging )
  3. HTTP Data Client – Web Scraping
  4. Page Speed Service: Web performance, delivered
  5. Forget eight cores. AMD is planning a 10-core desktop CPU for 2012.
  6. What if Chromebooks were made by Apple?
  7. Sun CEO explicitly endorsed Java’s use in Android: What do you say now Oracle?
  8. Scoop: Oracle scrubs site of embarrassing Java blog
  9. Juniper Networks adds former Microsoft president Muglia to the management ranks
  10. Microsoft updates Azure tookit for Apple’s iOS to support federation with Facebook, Google and more
  11. Microsoft and SUSE extend Microsoft’s controversial Novell Linux pact
  12. Too much JavaScript
  13. Easily write GPU accelerated programs
  14. 20 Database Design Best Practices
  15. Booting to the web
  16. Web Operations 101 For Developers
  17. Integrate Facebook logins in your Android app
  18. Poll: What’s the best route to writing mobile apps?
  19. Social coding — the next wave in development
  20. Cengage brings content, apps, and learning platforms to Moodle
  21. Google and OK Go team up in HTML 5 interactive video
  22. Windows 7 On The MacBook Air: Don’t Go There
  23. HTML5: Attributes, semantic markup, redefined elements
  24. Amazon, others cave to Apple on in-app purchases today, HTML5 tomorrow
  25. Experiment with the Latest HTML5 Technologies
    Read the rest of this entry »