How to create a single button flash audio player using Openlaszlo?

Hello Everyone,

I have been working on OpenLaszlo for quite sometime now and found it every easy to build custom flash widgets using it. In my first tutorial on OpenLaszlo, we will together learn a few specs of Openlaszlo and then code a tiny little flash media player.

Getting started with Openlaszlo:

  1. Openlaszlo is a framework which allows you to build flash widgets easily and faster. Biggest advantage is that you need not write any action scripting for building your flash widget. In laszlo we write code in XML format (files saved with extension .lzx) and then Laszlo server compiles our .lzx files to output a flash .swf file. WOW!
  2. Download your copy of laszlo from http://openlaszlo.org/download and install. If you are on windows, installation is simple. Just double click the downloaded .exe file and it will install everything for you. For me my installation is at C:OpenLaszlo Server 4.0.12
  3. Create a directory C:OpenLaszlo Server 4.0.12Serverlps-4.0.12Workspace . I generally do all my laszlo specific development under Workspace directory. (Adjust the path as per your installation)
  4. Create a folder inside Workspace named audioplayer
  5. Start the laszlo server.

Building an audioplayer in laszlo:

Before we proceed you may checkout the code repository from Google Code Base:

svn checkout http://abhinavsingh.googlecode.com/svn/trunk/ abhinavsingh-read-only

  1. As I wrote before, laszlo code files have an extension called .lzx . Lets first see a demo and then we will learn the syntaxes etc. You can find the explanation of the codes below within the code as comments
  2. Create a file called main.lzx and copy paste the following lines of code in it:
    <canvas id=”miniplayer” medialoadtimeout=”120000″ bgcolor=”#FFFFFF” debug=”true”>
     
      <!– This file takes care of toggling for the play/pause button –>
      <include href=”playpausemultibutton.lzx”/>
     
      <!– Include the MP3 player class –>
      <include href=”player.lzx”/>
     
      <!– Main view containing everything within it –>
      <view x=”5″>
        <simplelayout axis=”x” spacing=”5″/>
        <!– PLAY-PAUSE BUTTON PANEL –>
        <view name=”buttonpanel” id=”buttonpanel” y=”1″ bgcolor=”#EEEEEE”>
          <multistatebutton id=”playpausetoggle” name=”playpausetoggle” bgcolor=”#EEEEEE”
          resource=”playpause_rsrc” align=”center” statenum=”0″ statelength=”2″ maxstate=”1″ onclick=”this.toggle()”>
            <method name=”toggle”>
              if (this.statenum == 0) {
                this.setStateNum(1);
                <!– if players is already loaded with a song just play it, otherwise load it again with mp3url –>
                if(audioplayer.nowplaying == false) {
                  audioplayer.setAttribute(“nowplaying”,true);
                  audioplayer.setResource(global.mp3url);
                }
                else {
                  audioplayer.play();
                }
              }
              else {
                this.setStateNum(0);
                audioplayer.stop();
              }
            </method>     
          </multistatebutton>
        </view>
       
        <!– Include the audioplayer class –>
        <player id=”audioplayer” width=”100%” height=”100%”/>
       
      </view>
    </canvas>
  3. Create a file called playpausemultibutton.lzx and copy paste the following lines of code in it:
    <library>
      <resource name=”playpause_rsrc”>
         <!–  State: 0 –>
         <!– first  frame of state 1 = mouseup   image of the button –>
         <frame src=”icons/play_blue.png”/>
         <!– third  frame of state 1 = mousedown image of the button –>
         <frame src=”icons/pause_blue.png”/>

         <!–  State: 1 –>
         <!– first  frame of state 2 = mouseup image of the button –>
         <frame src=”icons/pause_blue.png”/>
         <!– third  frame of state 2 = mousedown image of the button –>
         <frame src=”icons/play_blue.png”/>
      </resource>
    </library>

  4. Create a file called player.lzx and copy paste the following lines of code in it:
    <library>
     
      <!– THE AUDIOPLAYER PLAYING CLASS –>
      <class name=”player” extends=”view” visible=”true” play=”false”>
       
        <!– Attribute which captures the player nowplaying stat –>
        <attribute name=”nowplaying” value=”false”/>
       
        <!– Attribute which captures the player loading stat –>
        <attribute name=”loading” value=”false”/>
       
        <!– Write ‘onlastframe’ handler –>
        <handler name=”onlastframe”>
          this.setAttribute(“nowplaying”,false);
          this.setAttribute(“loading”,false);
          playpausetoggle.toggle();
        </handler>
       
        <!– Write ‘onloadperc’ handler –>
        <handler name=”onloadperc” args=”p”>
          if(p > 0) {
           
          }
          if(p &lt; 1) {
            audioplayer.setAttribute(“loading”,true);
          }
          else if(p == 1) {
            audioplayer.setAttribute(“loading”,”done”);
          }
        </handler>
       
        <!– Write ‘onunload’ handler –>
        <handler name=”onunload”>
          if(this.nowplaying) {
            this.setAttribute(“nowplaying”,false);
            this.stop();
          }
        </handler>
       
        <!– Write ‘onplay’ handler –>
        <handler name=”onplay”>
          this.setAttribute(“nowplaying”,true);
        </handler>
       
        <!– Write ‘onload’ handler –>
        <handler name=”onload”>
        </handler>
       
        <!– Write ‘onframe’ handler –>
        <handler name=”onframe”>
        </handler>
       
        <!– Write ‘onstop’ handler –>
        <handler name=”onstop”>
        </handler>
       
        <!– Write ‘ontimeout’ handler –>
        <handler name=”ontimeout”>
        </handler>
       
      </class>
     
    </library>
  5. Create a file called mediaplayer_dev.html and copy paste the following lines of code in it: (This is development environment file, mediaplayer.html is the production environment file which you can find in code repository)
    <html>
      <head>
        <title>Flash Audio Player</title>
        <script type=”text/javascript” src=”swfobject.js”></script>
      </head>
      <body>
        <div id=”flashcontent” width=”100%”>
          This text is replaced by the Flash movie.
        </div>
        <script type=”text/javascript”>
          var so = new SWFObject(“main.lzx?lzt=swf&debug=true”, “singlebuttonplayer”, “100%”, “100%”, “7”, “#FFFFFF”);
          so.addParam(“quality”, “high”);
          so.addParam(“scale”, “exactfit”);
          so.addParam(“salign”, “LT”);
          so.addParam(“menu”, “false”);
          so.addParam(“wmode”, “opaque”);
          so.addParam(“allowScriptAccess”, “always”);
         
          //Set the mp3urlfor the song
          so.addVariable(“mp3url”,”http://127.0.0.1:8080/lps-4.0.12/Workspace/audioplayer/Liquid Tension Experiment – Acid Rain.mp3″);
         
          so.write(“flashcontent”);
        </script>
      </body>
    </html>
  6. Create a folder called icons and copy the two icons which you checked out from the code repository.
  7. Copy an mp3 file from your hard disk and copy paste it in the folder. Then edit the mp3url in above code of mediaplayer_dev.html
  8. Copy and paste the swfobject.js file which you have checked out from code repository.

That all we need to test run our single button audio player. Now simply open the following URL in your browser: (edit it as per your folder names)
http://127.0.0.1:8080/lps-4.0.12/Workspace/audioplayer/mp3player_dev.html
and you can see the audio player playing your mp3 song 🙂

Now we can see our file playing the mp3 well and we would like to generate a flash file out of our main.lzx file. For this laszlo have their inbuild compilers which will compile the flash file for you. Simply open the url:
http://127.0.0.1:8080/lps-4.0.12/Workspace/audioplayer/main.lzx
and then check swf8 at the bottom of the page under compile options and press compile

From here on you have two options:

  1. Either to use laszlo specific embedding strategy i.e. If you proceed with further steps after pressing compile, laszlo will give you a set of javascript files which you can use to embed your audio player.
  2. Or you can use swfobject.js to embed your flash files in your website. (Recommended)

I assume you will use swfobject.js and in that case you may simply stop after pressing compile. See the folders and you can see  two .swf files being generated into the folder. These are our final production level flash audio player files.

Now lets see how to use these .swf files in our pages. Simply rename them to alterplayer.swf and create a file called mediaplayer.html and copy paste the below code in it:

<html>
  <head>
    <title>Flash Audio Player</title>
    <script type=”text/javascript” src=”swfobject.js”></script>
  </head>
  <body>
    <div id=”flashcontent” width=”100%”>
      This text is replaced by the Flash movie.
    </div>
    <script type=”text/javascript”>
      var so = new SWFObject(“alterplayer.swf”, “singlebuttonplayer”, “100%”, “100%”, “7”, “#FFFFFF”);
      so.addParam(“quality”, “high”);
      so.addParam(“scale”, “exactfit”);
      so.addParam(“salign”, “LT”);
      so.addParam(“menu”, “false”);
      so.addParam(“wmode”, “opaque”);
      so.addParam(“allowScriptAccess”, “always”);
     
      //Set the mp3urlfor the song
      so.addVariable(“mp3url”,”http://mysite.com/songname.mp3″);
     
      so.write(“flashcontent”);
    </script>
  </body>
</html>

We did not much change from mediaplayer_dev.html. Simply replaced .lzx file with actual .swf file and the mp3url also change to your production level mp3 url.

Thats pretty much of what we actually wanted to have. 🙂

In future we will see how to build a:

  1. Single Button Player which also shows the time
  2. Single Button Player with progress bar and volume control
  3. Audio Player capable of playing a whole mp3 playlist.
  4. Audio Player with AJAX search enabled in it.

If you want to see the final version of flash player which we will slowly learn to develop, kindly visit Altertunes (my first ever site :))

Kindly let me know if you are having trouble in learning and running this player. I will more than happy to contribute and share further.

Document Reference:

  1. http://www.openlaszlo.org/lps4/docs/
  2. http://www.openlaszlo.org/lps3/docs/reference/
  3. You can find some great help from the official forum http://forum.openlaszlo.org/

Let me know your feedbacks.

Essential frameworks for web development

Hello developers,

Initially when I started working on Altertunes, I was unaware of the various frameworks which one can use for his website. Though I never have used any of them for Altertunes (main reason being the eagerness to do everything by myself), but may be some of you out there might be interested in having a look at the same:

  • http://prototypejs.org : Undoubtedly one of the best available framework for Ajax in the market. Prototype is a javascript framework that aims to ease development of dynamic web applications.
  • http://script.aculo.us : If you are looking to have all those fade-in and fade-out effects for your website, probably Scriptaculous does the best for your website. Scriptaculous provides you with easy-to-use, cross-browser user interface JavaScript libraries to make your web sites and web applications fly. Though I am not too sure, but I guess Ruby on Rails already comes packaged with Scriptaculous.
  • Prototype Windows Class : Another master piece which allows your website to have all those fancy popups, fade-in and fade-out effect.
  • Google Web Toolkit : Google Web Toolkit (GWT) makes it easier to write high-performance AJAX applications. You write your front end in the Java programming language and GWT compiles your source into highly optimized JavaScript.

Probably you will find hundred’s of them in the market right now. Above I have listed a few which I tried atleast once and got good performance. However there are various factors which decide what Ajax framework you should choose for your site. Most important being:

“It seems that a very light framework is required for a public site. If your visitors need to upload a large Javascript API, they may not visit further your website, depending on your page’s download times. When working on intranets, or professionnal services, it may be acceptable that the first access to the application may be longer, moreover when the website is used daily. Also think about on-demand Javascript and Javascript compression.” – by Michael Mahemoff

If you are looking to develop your site using flash, then there are again some excellent frameworks available in the market for the same. Two of the best which I know are:

  • OpenLaszlo : OpenLaszlo is an open source platform for creating zero-install web applications with the user interface capabilities of desktop client software. OpenLaszlo programs are written in XML and JavaScript and transparently compiled to Flash and DHTML. The Alterplayer used on Altertunes, was developed by me using OpenLaszlo. I am open for any suggestion or question you need for development in OpenLaszlo.
  • Red5 : It is an opensource flash server written in Java that supports Streaming audio and video, recording client streams and many other useful things which openlaszlo fails to do currently. So if you are looking to develop a voice chat application, Red5 is the way to go.

Above are just a few which I found useful on my way to Altertunes. There are several more untouched by me, which might be more powerful than the those I have listed above. If you find any, kindly post the same as comment here.

Happy Frameworking and web developement 😉

Web Development – Part 1: Apache, MySQL, PHP

Hello Friends,

Ever since I have started web development and launched Altertunes, many of my friends have asked me, “How and Where to start web development ?” . Though there are infinite tutorials over the internet on web development, I will try to jot down my experiences and learnings here.

To start with, I will just try to explain a few terms, before we go on and learn how to handle and integrate them together:

  1. Apache: is the web server, which is used world wide for web development. Since April 1996 Apache has been the most popular HTTP server on the World Wide Web. However, since November 2005 it has experienced a steady decline of its market share, lost mostly to Microsoft Internet Information Services. As of April 2008 Apache served 50.42% of all websites.
  2. MySQL: is a multi threaded and multi-user SQL database management system, which has more than 11 million installations. MySQL is popular for web applications and acts as the database component of the LAMP, BAMP, MAMP, and WAMP platforms (Apache-MySQL-PHP/Perl/Python on Linux/BSD/Mac/Windows), and for open-source bug tracking tools like Bugzilla. It’s popularity for use with web applications is closely tied to the popularity of PHP and Ruby on Rails, which are often combined with MySQL. PHP and MySQL are essential components for running popular content management systems such as Joomla, WordPress, Drupal, and some BitTorrent trackers. Wikipedia runs on MediaWiki software, which is written in PHP and uses a MySQL database.
  3. PHP: is a widely-used, general-purpose scripting language that is especially suited for web development and can be embedded into HTML. It generally runs on a web server, taking PHP code as its input and creating web pages as output. It can be deployed on most web servers and on almost every operating system and platform, free of charge. PHP is installed on more than 20 million websites and 1 million servers, although the number of websites with PHP installed has declined since August 2005. It is also the most popular Apache module among computers using Apache as a web server. The most recent major release of PHP was version 5.2.6 on May 1, 2008.

In short, Apache is the web server which serves the web pages for the website. MySQL is the database which is used to store necessary information ranging from user’s data to user’s pictures. PHP is the server side scripting language used to make web pages. Apache server takes PHP code as input, and outputs an HTML page on the browser.

Lets start some installations and configurations: If you don’t want to handle the installations and configurations of WAMP (Apache-MySQL-PHP on Windows), you may choose to download and install the pre-packaged installer from here. However its always better to configure things yourself to know the inner details. If you are brave enough to install and configure these modules, here we go:

  • Apache Installation: Go to http://httpd.apache.org/download.cgi and download the latest Win32 Binary including OpenSSL (MSI Installer) version of Apache Server Installer Available. Double click the installer and you should see something like this:

    Click next and after a few clicks you will be asked for the following parameters:

    Fill in the details, as shown in the figure above , choose installation type as ‘Typical’ and proceed to install the Apache server.

    Open up your favorite browser and type in http://localhost. If you see a page that says “It works!” then the Apache server has been installed successfully.

  • PHP Installation: Go to http://www.php.net/downloads.php and download the latest PHP Zip Package. Unzip the file into your C: drive, and rename the folder to C:PHP. Next copy the file C:PHPphp.ini-dist file to C:Windows and rename the file it C:Windowsphp.ini. This is the PHP Configuation file where we will be setting some of the important parameters later on.Now its time to integrate PHP with Apache we installed earlier. Open the Apache configuation file (Important: you should always have a copy of this file stored somewhere else, because an error or misconfiguration can cause your Apache server to crash!), which is located at C:Program FilesApache Software FoundationApache2.2confhttpd.conf into notepad and copy the following lines at the end of ‘LoadModule’ section in the configuration file:

    #AddType application/x-httpd-php .php
    LoadModule php5_module “C:/PHP/php5apache2.dll”
    AddType application/x-httpd-php .php .phtml .inc .php3
    AddType application/x-httpd-php-source .phps
    # configure the path to php.ini
    PHPIniDir “C:/Windows”

    Now lets configure the root directory of our Apache server. Root directory is the base directory from where the website is served. When you type in http://localhost in your browser, the server looks for the necessary files in the root directory and serves it to the browser. By default, the root directory of the Apache server is set to : C:Apache2htdocs. You may keep the root as C:Apache2htdocs or you may change it to a directory of your choice as follows:

    Look for the ‘DocumentRoot’ Section in the Apache configuration file located here: C:Program FilesApache Software FoundationApache2.2confhttpd.conf. You should see something like this:

    # DocumentRoot: The directory out of which you will serve your
    # documents. By default, all requests are taken from this directory, but
    # symbolic links and aliases may be used to point to other locations.
    DocumentRoot “C:Apache2htdocs”

    Change C:Apache2htdocs to a directory of your choice, anywhere on your computer. For eg. C:Workspace.

    Further scroll down in the httpd.conf file and search for a section which looks like this:

    # This should be changed to whatever you set DocumentRoot to.
    <Directory “C:Apache2htdocs”>

    Change the directory location from C:Apache2htdocs to whatever you have set in the step before.

    Now to test whether everything is configured correctly, create a file in the root directory of Apache server, named phpinfo.php and paste the following code into it:

    <?php phpinfo(); ?>

    Restart your Apache server from here Start > All Programs > Apache HTTP Server > Control Apache Server > Restart, and open the following URL in your browser: http://localhost/phpinfo.php . If everything is well setup and you are lucky enough, you will see something like this:

    Finally, we just need to make a few configurations in the PHP configuration file which we copied to C:Windowsphp.ini. Open the file in a text editor and find the section which looks like this:

    ; Directory in which the loadable extensions (modules) reside.
    extension_dir = “./”

    Change it to look like this:

    ; Directory in which the loadable extensions (modules) reside.
    extension_dir = “C:PHPext”

    Also, find the section in your PHP configuration file which looks like this:

    session.save_path = “/tmp”

    and change it to:

    session.save_path = “C:WINDOWStemp”

    And finally we come to the end of PHP installation section. Congratulations, Good going !

  • MySQL Installation: Go to http://dev.mysql.com/downloads/mysql and download the latest MySQL database. Once ZIP file has finished downloading, extract it using WinZIP or a similiar program on your computer. Double click the setup.exe file to start the installation. You should see something like this:Keep clicking next and keep all the default options (use typical installation and not the detailed one). After installation finishes, go to start -> run -> services.msc and start the MySQL service. (If MySQL service doesn’t exist, the installation was not successful) . Now we need to tell PHP that MySQL exists on your system, and we need to integrate them. Go to php.ini i.e. the PHP configuration file, and make the following changes:

    Search for something like this:
    ;extension=php_mysql.dll

    and make it like this:
    extension=php_mysql.dll (i.e. you just need to remove the semicolon)

    Additionally you need to add this:
    extension=php_mysqli.dll

    at the end of the extensions. Further copy:
    libmysql.dll to C:WindowsSystem32 and restart Apache.

  • PHPMyAdmin and MySQL Query Browser Installation: Though you can always use MySQL database through command line but having PHPMyAdmin or MySQL query browser will make your database management a lot easier and simple. To install download PHPMyAdmin from here. Download the ZIP file and extract it under the root directory of Apache Server, i.e. if root directory is set as C:Workspace , the extracted PHPMyAdmin folder’s location should have a path C:Workspacephpmyadmin.Open the config.ini.php file in the PHPMyAdmin folder and make the following changes:$cfg[‘Servers’][$i][‘user’] = ‘root’;
    $cfg[‘Servers’][$i][‘password’] = ‘YOUR_PASSWORD’; // Your MySQL Password
    /* Authentication type */
    $cfg[‘Servers’][$i][‘auth_type’] = ‘config’;
    /* Server parameters */
    $cfg[‘Servers’][$i][‘host’] = ‘localhost’;
    $cfg[‘Servers’][$i][‘connect_type’] = ‘tcp’;
    $cfg[‘Servers’][$i][‘compress’] = false;
    /* Select mysqli if your server has it */
    $cfg[‘Servers’][$i][‘extension’] = ‘mysql’;
    /* User for advanced features */
    $cfg[‘Servers’][$i][‘controluser’] = ‘root’;
    $cfg[‘Servers’][$i][‘controlpass’] = ‘YOUR_PASSWORD’; // Your MySQL Password
    /* Advanced phpMyAdmin features */
    $cfg[‘Servers’][$i][‘pmadb’] = ‘phpmyadmin’; //Name of PHPMyAdmin folder
    $cfg[‘Servers’][$i][‘bookmarktable’] = ‘pma_bookmark’;
    $cfg[‘Servers’][$i][‘relation’] = ‘pma_relation’;
    $cfg[‘Servers’][$i][‘table_info’] = ‘pma_table_info’;
    $cfg[‘Servers’][$i][‘table_coords’] = ‘pma_table_coords’;
    $cfg[‘Servers’][$i][‘pdf_pages’] = ‘pma_pdf_pages’;
    $cfg[‘Servers’][$i][‘column_info’] = ‘pma_column_info’;
    $cfg[‘Servers’][$i][‘history’] = ‘pma_history’;

    Now open the url, http://locahost/phpmyadmin and if everything is configured correctly you must see something like this:

And thats it, if you are able to see all the above images on your computer, it means you have just configured everything correctly and you are all setup for web development.

I have installed and configured all the components way back (6 months ago), hence there is a possibility that I might have missed out on some trivial points. If you catch hold of any such issue do comment the same.

Enjoy making cool webpages, and All the best for your website 🙂