Click or scroll down Circle me on Google+ Fork me on GitHub Follow me on Twitter Ask me on Stack Overflow Gild me on Reddit Code Ninja, Entrepreneur, Idiot ChalkHQ — consulting, prototyping, mentoring HighF.in — resolve innefficiencies in your startup's workflow DearDrum.org — online open-mic / creative space The Dirac Equation (click to WikiPedia) A maxim Sun Tzu references in his magnum opus The Art of War

If you know the enemy and know yourself, you need not fear the result of a hundred battles.
If you know yourself but not the enemy, for every victory gained you will also suffer a defeat.
If you know neither the enemy nor yourself, you will succumb in every battle.
Fork me on GitHub

Tags

actionscript ad-hoc networks Adobe AIR anonymous Apple array Browsing convert Debugger Error Facebook file permissions Flash Flex fonts function future Google Google Plus grid hackers html javascript logs loop network p2p php privacy regexp Security Server social ssl technology terminal time Twitter upgrade Web 2.0 Web 3.0 Web 4.0 Web 5.0 wordpress

Featured Posts

  • Javascript: Undefined parameters
  • The Web, A Look Forward
  • Let Postfix send mail through your Gmail Account – Snow Leopard
  • Archives

  • April 2013
  • December 2011
  • July 2011
  • June 2011
  • March 2011
  • February 2011
  • January 2011
  • November 2010
  • October 2010
  • September 2010
  • July 2010
  • May 2010
  • Categories

  • Code
  • Design
  • Opinion
  • Security
  • Tools
  • Uncategorized
  • Tag: actionscript

    Why I Chose OGG Vorbis as the Audio Format on DearDrum.org

    This is from http://deardrum.org/about/html5

    What is HTML5 and why do I need it?

    To put it simply HTML is what websites are made of. HTML5 is just the newest version.

    DearDrum.org uses some pretty advanced stuff under the hood that's only available in HTML5. So in order to play audio on the site and do some other cool things you need a Web Browser that understands HTML5. (more on this below)

    Fortunately there are a few really amazing web browsers out there that do support HTML5 really well. And if you're not comfortable switching to a new browser there's probably a plugin for your browser to get you on board.

    Here are some quick links so you can get started, you only need one, but why not try them all if you have time. I'll go into a bit more detail and walk you through the issues below that if you're interested or confused by any of this.

    Links:

    Google Chrome is - in our professional opinion - the best web browser out there, hands down.
    Download Google Chrome

    Firefox is phenomenal too, and by far the most widely used browser that supports HTML5.
    Download Firefox

    Internet Explorer is, well, incompatible with everything. Google made a plugin called Chrome Frame which brings HTML5 to Internet Explorer. Despite some recent claims to the contrary IE9 will never support HTML5 by itself and requires Chrome Frame in all cases (more on this below).
    Download Google Chrome Frame for Internet Explorer

    Safari is in the same boat as Internet Explorer with regards to HTML5. They claim to support it but intentionally cripple its functionality. On a Mac you can install a plugin called XiphQT which will bring you up to speed. On Windows you'll need to switch to another browser to get proper HTML5 support.
    Download the XiphQT plugin for Mac

    Opera is a less known web browser that totally supports HTML5, and we love them for it.
    Download Opera

    So What is a Web Browser?

    Yeah yeah, I get it. Now What is HTML5? Really.

    You may have seen the code that makes up web pages. If you right click on this page you should see an option to view the source code of the page. That's HTML. Now the internet is an open place and as you can see there are lots of different browsers. So everyone kind of has to agree on the specifics of the HTML language. The specs for HTML5 aren't finalized yet but some of the more advanced browsers are already supporting most of HTML5 already. There is however a big argument going on surrounding HTML5 audio and video.

    At the end of the day HTML5 will have to be open, because the web needs to be open. Imagine if you had to pay $5000 a month to use Google, and that money wasn't even to pay Google, it went to some licence holder who owned use of the letter E... That would be terrible and there'd be no innovation on the web. There'd have been no Facebook or WikiPedia, and no DearDrum.org.

    What exactly is this HTML5 argument about?

    Up until now HTML has not had any built in support for audio or video. If you wanted to play audio or video on the web you had to use a plugin like Adobe Flash Player. Which is fine, but Adobe is a profit motivated company and the web is an open place, so in the interest of choice and freedom the new version of HTML, HTML5 does have built in audio and video support.

    Now the standards body that decides on what HTML5 will be is called W3C. Unfortunately the W3C is dominated by massive corporations who tend to dictate the standards in favour of their profit margin instead of what's best for an open, innovative web, and what's best for all of us. Up until now there hasn't really been much to debate over and it's been a long time since HTML4 came out anyway. Up until now Internet Explorer had majority market share and deliberately didn't follow the standards so web developers would have to focus on supporting IE's defunked and broken interpretation of HTML4. IE's massive market share was purely the result of being packaged with Windows. Microsoft has been sued over this anti-competitive practice because it directly hurt the web for so many years. During this time the other web browsers pushed to become faster and add amazing features to try gain as much market share as possible. It was IE vs. the world and Mozilla was their biggest rival with Firefox. If it wasn't for Firefox we'd all be eating dirt and living in shacks right now in a world where an open DearDrum.org could never even be conceived of.

    The problem with HTML5 audio/video support is that everyone needs to agree on an audio and video format; in the same way .txt is a text format and .jpg is an image format. The issue is licensing. There happen to be some really great audio and video formats out there that are open source, meaning they can be freely used and improved upon by anyone. There also happen to be a lot of big faceless corporations in the W3C, see a list here, some of whom own part of the licensing rights to a particular format known as H.264.

    When it comes to web browsers you have two sides of the argument. Those for an open web, and those whom want to charge everyone obscene amounts of money to use H.264. Currently the H.264 license allows people to use it. This free use has been extended to 2016 for the purposes of convincing non owners in the W3C - and the greater public, that it's free. After 2016 and quite frankly with the right high priced law firm any old time, that could expire and everyone would suddenly be charged $50 a day to watch youtube videos. Or $5000 a year to upload YouTube videos. If H.264 becomes the standard it would be a twisted joke and we would all be royally screwed.

    Microsoft and Apple both own part of the H.264 licensing rights. So they've chosen only to support that format. They could easily support both H.264 and WebM(the open, free format), but they don't because they're hoping that they can prolong the debate long enough that developers will have to support H.264 to reach the majority of people who use those two browsers - both packaged and preinstalled with their respective operating systems.

    Mozilla by it's very nature will always push for an open web, and Google's profit margin is directly tied to people's ability to generate content. Google went so far as to purchase the WebM format AND absolve the entire world from licensing fees should some obscure patent be discovered down the road and some sadistic person try capitalize on it. To Google it's a business expense, but it happened and it benefits everyone.

    The WebM format is a container format, which uses VP8 for video, and OGG Vorbis for audio. For DearDrum.org we decided to use OGG Vorbis as our audio format.

    Wow that was a lot to take in, so why does DearDrum.org use OGG Vorbis instead of MP3?

    While most your music is probably in .mp3 format, it costs a lot of money to transcode audio into the .mp3 format due to licensing. And who knows when that price will go up. When creating DearDrum.org I didn't want to be at the mercy of some company, and we didn't want to charge people to download and use the DearDrum.org Desktop App. We went in favour of choice, freedom, and openness because we value those ideals; and we want the web to remain an innovative grounds for inspiring new ideas.

     

    Weird Flex Error #2006

    I was getting this weird error whenever switching from a given state to it's parent state in a Flex 3.5 based project.

    RangeError: Error #2006: The supplied index is out of bounds.
    	at flash.display::DisplayObjectContainer/addChildAt()
    	at mx.core::Container/addChildAt()
    	at mx.effects::EffectManager$/removedEffectHandler()
    	at Function/http://adobe.com/AS3/2006/builtin::apply()
    	at mx.core::UIComponent/callLaterDispatcher2()
    	at mx.core::UIComponent/callLaterDispatcher()

    It threw me for a minute because I hadn't made any changes to effects since I last tested the application and I couldn't see any connection between the code I had just written and any effects in the app. But after hunting around I found the culprit. There's a set of components in a Canvas that gets removed when moving to the parent state. What I had done was separate those components into two Canvases(Canvi?). For whatever crazy reason the new second Canvas can't have a RemoveEffect. The code works fine if just the first Canvas has it, but if both or just the second Canvas has it then it throws that error.

    side note: the reason it took me a while to find the source of the error was because I copy/pasted the canvas declaration only changing the id, and I forgot that there was a removedEffect associated with it.

    But wait there's more. The reason I split the components into two distinct Canvases was so I could position one below and the other on top of a third major component in z-space. The solution was to add the first Canvas as a "firstChild" and the second Canvas as a "lastChild". That it seems was the problem. In mxml when changing states you apparently can't add a firstChild before adding a lastChild. so I copy and pasted the first Canvas below the second one, so that all the lastChild additions occurred before all the firstChild additions and voila, presto, it works.

    The reason is that when you move from a state back to its parent state it follows the order in which you add components in the state declaration to remove them. If the first component you add is added as a firstChild then that get's removed first changing the indexes and number of children of the parent container. I guess the underlying state changing function already calculated what the lastChild index was, so when trying to remove a Child with the pre-calculated index of lastChild it triggered an index out of bounds error.

     

    Flash Snippets for Flash Builder 4

    I'm getting used to Flash Builder 4, man is it fast. I came across this plugin by Lee Brimlow, it's SnipTreeView adapted to work with .mxml files and in FB4. Just download it from his blog and add it to the plugins folder, then restart. There's a quick video how to, highly recommended.

    Flash Snippets [http://theflashblog.com/?p=1494]

     

    Flex/Actionscript 3.0 Strip HTML Tags Function

    I needed a function to strip out html tags from a text input, but still let me specify allowable tags.

    Instead of spending time figuring out the regular expressions needed to pull it off and becoming a better programmer, I figured why repeat work someone else has probably already done.. I mean I could be a busy man. Anyway I found this great function on Flexer.info [link]. But after trying it out I noticed that the one tag I really really wanted to be parsed out iframe wasn't. It seems because I had specified i as an allowable tag it was also accepting iframe.

    So with all due respect to Andrei, below is the revised function with the security hole patched.

    All I changed was near the bottom where it determines if it's an allowable tag or not the reg exp was

    <\/?" + tagsToKeep[j] + "[^<>]*?>

    which allowed any character to follow the allowed tag as long as it wasn't a nested tag, which included frame following i. This will also support self closing tags.

     
    // strips htmltags
    // @param html - string to parse
    // @param tags - tags to ignore
    public static function stripHtmlTags(html:String, tags:String = ""):String
    {
        var tagsToBeKept:Array = new Array();
        if (tags.length > 0)
            tagsToBeKept = tags.split(new RegExp("\\s*,\\s*"));
    
        var tagsToKeep:Array = new Array();
        for (var i:int = 0; i < tagsToBeKept.length; i++)
        {
            if (tagsToBeKept[i] != null && tagsToBeKept[i] != "")
                tagsToKeep.push(tagsToBeKept[i]);
        }
    
        var toBeRemoved:Array = new Array();
        var tagRegExp:RegExp = new RegExp("<([^>\\s]+)(\\s[^>]+)*>", "g");
    
        var foundedStrings:Array = html.match(tagRegExp);
        for (i = 0; i < foundedStrings.length; i++)
        {
            var tagFlag:Boolean = false;
            if (tagsToKeep != null)
            {
                for (var j:int = 0; j < tagsToKeep.length; j++)
                {
                    var tmpRegExp:RegExp = new RegExp("<\/?" + tagsToKeep[j] + " ?/?>", "i");
                    var tmpStr:String = foundedStrings[i] as String;
                    if (tmpStr.search(tmpRegExp) != -1)
                        tagFlag = true;
                }
            }
            if (!tagFlag)
                toBeRemoved.push(foundedStrings[i]);
        }
        for (i = 0; i < toBeRemoved.length; i++)
        {
            var tmpRE:RegExp = new RegExp("([\+\*\$\/])","g");
            var tmpRemRE:RegExp = new RegExp((toBeRemoved[i] as String).replace(tmpRE, "\\$1"),"g");
            html = html.replace(tmpRemRE, "");
        }
        return html;
    }

     

    Convert Milliseconds to Time (H:M:S)

    Converting milliseconds to a time string can be a pain, especially when you're measuring something dynamic. In most languages I've come accross the Date object is calculated by the number of milliseconds that have passed since Jan 1, 1970. Because the different parts of a date are based on different bases ie: 60 minutes in an hour, 24 hours in a day etc. It's a lot easier to get the milliseconds passed since Jan1, 1970 and work with that value. This only works if you want to get the difference between two dates. If you were to subtract two dates(expressed as milliseconds) and get 432000000 milliseconds(5 days), then convert that to a Date object, the code would interpret 432000000 as Jan 6, 1970.

    In another scenario I was just writing a podcast player in Flex 3/AIR and wanted to convert the Sound.length and SoundChannel.position values, both of which are measured in milliseconds, and display the length and current position of the episode in formats that would make sense. So I wrote a generic function that accepts millisecondsas an argument and returns the formatted time string.

      /**    Milliseconds to Time String in Flex 3              **/
      /**    Author: Yoav Givati [http://fightskillz.com]       **/
    
    public function fnMillisecondsToTimeCountUp(time:Number):String {
    
    	//calculate playtime from milliseconds
    	var h:Number = new Number(Math.floor(time/1000/60/60));
    	//minutes left shows total minutes left plus hours, 1h5m = 65mins
    	//so we subtract the amount of 60's added by the hours to get just minutes
    	var m:Number = new Number(Math.floor(time/1000/60)-(h*60));
    	//seconds left
    	var s:Number = new Number(Math.floor(time/1000)-(m*60));
    
    	//create string variables
    	var hours:String;
    	var minutes:String;
    	var seconds:String
    
    	//make sure minutes and seconds are always two digits
    	if(m.toString().length == 1) {
    		 minutes = "0"+m;
    	} else {
    		 minutes = m.toString();
    	}
    
    	if(s.toString().length == 1) {
    		seconds = "0"+s;
    	} else {
    		seconds = s.toString();
    	}
    
    	//if hours or minutes are 0 we don't need to see them
    	if(h == 0) {
    		hours = '';
    		if(m == 0) {
    			minutes = '';
    		} else {
    			minutes = minutes+":";
    		}
    	} else {
    		hours = h+":"
    		minutes = minutes+":";
    	}
    
    	// after 1 hour passes the seconds become 4 digits long
    	// the last two of those digits represent the actual seconds
    	seconds = seconds.slice(seconds.length-2, seconds.length);
    	return hours+minutes+seconds;
    
    }

    You'll notice that I'm using Math.floor(), it's crucial that you round down, because the way the hours are being calculated for example, rounding up would show one hour had passed after only a fraction of an hour, just rounding up the minutes or seconds would cause everything to be out of sync and the math would be concussed. For those of you who are confused I should clarify that Math.floor(1.8) would return a value of 1 and Math.ceil(1.3) would return a value of 2, the term 'round' is probably a misleading. If you were using this function to count down instead of up, you would useMath.ceil()(although still not for the hour value), you essentially want to stay on the 'other side' of the minute or second for as long as possible.