MP3 waveforms with PHP

If you are thinking how generates the waveform for sound MP3 player?


There are some audio processing libraries used to process MP3 files to WAV and then PNG / SVG images..

MP3 to WAV to PNG

1. LAME MP3 encoder/decoder

$ lame input.mp3 -f -m m -b 16 –resample 8 resampled.mp3 && lame –decode resampled.mp3 output.wav

2. SOX – Sound eXchange

$ sox output.wav −n spectrogram
$ sox output.wav -n spectrogram -Y 140 -l -r -o output.png

3. wav2png – Creates waveform pngs out of audio files

$ sox mp3-song.mp3 -c 1 -t wav – | wav2png -o mp3-song.png /dev/stdin
$ wav2png –foreground-color=2e4562ff –background-color=00000000 -o  output.png   input.wav

4. wavesurfer.js is a customizable audio waveform visualization, built on top of Web Audio API and HTML5 Canvas


<script src=""></script>
<script src=""></script>
<script src=""></script>

<div id="waveform"></div>


var wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: '#00FF00',
progressColor: '#FF0000'


wavesurfer.on('ready', function () {;
$('.waveform__duration').text( formatTime(wavesurfer.getDuration()) );

wavesurfer.on('audioprocess', function () {
$('.waveform__counter').text( formatTime(wavesurfer.getCurrentTime()) );


WaveForm generated using SOX

WaveForm Generator using SOX


Create Website Thumbnails using PhantomJS

Hope you read my old article “Create WebThumb using LAMP”, it used for creating web thumbnails from Xvfb virtual framebuffer that is more time and resource consuming.

Shell Script with Xvfb try to open web browsers in real remote server to capture web-thumbs…

That whole setup might take a full day and image quality is very bad….

Thanks to PhantomJS

PhantomJS is a headless WebKit with JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.

Simple Javascript example

console.log(‘Loading a web page’);
var page = require(‘webpage’).create();
var url = ‘’;, function (status) {
//Page is loaded!


– Headless Website Testing
– Screen Capture
– Page Automation
– Network Monitoring

Fork on Github

PhantomJS is using WebKit for a real layout and rendering engine, it can be used to capture web page as screenshot or PDF files. PhantomJS can render anything on the web page, it can be used to convert contents in HTML/CSS, SVG and Canvas.

// Thumbnail of Webpage using webthumb.js

var page = require('webpage').create(),
    system = require('system'),

if (system.args.length !== 3) {
    console.log('Usage: webthumb.js webURL filename');
    console.log('Usage: webthumb.js svnlabs.png');
} else {
    weblink = system.args[1];
    fname = system.args[2];    
    page.viewportSize = { width: 320, height: 480 };, function (status) {
    if (status !== 'success') {
        console.log('Unable to open webpage!');
    } else {
    window.setTimeout(function () {
    }, 3000);

Download webthumb.js

# phantomjs webthumb.js svnlabs.png
# phantomjs webthumb.js svnlabs.pdf

You can even capture webpage as good quality PDF file 😉



You can also use examples/rasterize.js for same sort of functions 😉

# phantomjs examples/rasterize.js svnlabs.png
# phantomjs examples/rasterize.js ‘’ svnlabs.pdf

rasterize.js – rasterizes a web page to image or PDF
render_multi_url.js – renders multiple web pages to images
technews.js – captures Google News as a PNG image

SoundCloud Application

Connect the World of Sound

* Share :
* Stream :
* Customize :

SoundCloud Widgets

API | Javascript SDK | Widget | Custom Player | oEmbed

API Wrapper for SoundCloud written in PHP with support for authentication using OAuth 2.0

try {
    $response = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {


Demo Apps

There are many sound applications built using the SoundCloud API.

Install Etherpad on SUSE Linux

Collaborate on documents in really real-time on SUSE Linux

EtherPad is the first web-based word processor that allows people to work together in really real-time.

All editing of the document is instantly visible on the screens of all participating users, enabling new and productive ways to collaborate on text documents. Etherpad is useful for meeting notes, drafting sessions, education, team programming, and more…

1. Online word-processor with formatting options
2. Letter by letter collaboration
3. Color-coded edits
4. Infinite Undo
5. History Playback
6. Import HTML, Word, RTF
7. Export as HTML, Word, PDF
8. Change Zoom
9. Super simple to embed into your own website/CMS with jQuery and PHP examples
10. Support with PHP, jQuery, Elgg, Apple devices, JavaScript, Ruby, Python etc.

Instructions for compiling and running the EtherPad open source release

How we can install Etherpad on Open SUSE Linux?

I just want to help you out… If you want to pay me nothing that is fine too! 😉

Here are some simple steps to install Etherpad on Open SUSE Linux…..

SUSE Linux is different from RedHat, CentOS or Ubuntu. General Package Managers / Setup Tool won’t work on SUSE, It support Zypper or YaST.

First check your server architecture

# uname -a

# cd /usr/local

Java 1.6 (tested with 1.6.0_20)
Scala 2.7 (tested with 2.7.7)
MySQL Server 5.1 (tested with 5.1.59)
mysql-connector-java (tested with 5.1.18)

Create username ‘etherpad’ with password ‘password’

# useradd -r -m etherpad
# passwd etherpad

Install Java

# uname -a
I am using 32-bit here…
# wget
# sh jdk-6u20-linux-i586-rpm.bin

# java -version

Install fastjar

# zypper install fastjar
# yast –install fastjar
# yast2 –install fastjar

Download Scala

# wget
# tar xvzf

Install MySQL

# zypper install mysql-server
# service mysqld start
# chkconfig mysqld on

Download MySQL Java Connector


# zypper install mysql-connector-java


# wget
# tar xvzf mysql-connector-java-5.1.18.tar.gz

Install MER­CU­R­IAL .. OR GIT

# zypper install mercurial

# zypper install git

Make sure port 9000 must be open on IPTABLES / Firewall

# /etc/sysconfig/iptables

-A RH-Firewall-1-INPUT -p tcp -m state –state NEW -m tcp –dport 9000 -j ACCEPT

Various scripts make assumptions about environment variables:

JAVA should be set to the java executable.
JAVA_HOME should be set to the main jdk directory.
SCALA should be set to the scala executable.
SCALA_HOME should be set to the main scala distribution directory.
PATH should contain $JAVA, $SCALA, and mysql
MYSQL_CONNECTOR_JAR should be set to the mysql-connector JAR file included in the mysql-connector download.
For example, this sets up the environment on my machine:

# touch myENV
# vi myENV

export JAVA_HOME=/usr/java/jdk1.6.0_20/
export JAVA=$JAVA_HOME/bin/java
export SCALA_HOME=/usr/local/scala/
export SCALA=$SCALA_HOME/bin/scala
export MYSQL_CONNECTOR_JAR=/usr/local/mysqlconnector/mysql-connector-java-5.1.18-bin.jar

# cat myENV >> /etc/profile

Download EtherPad

# hg clone etherpad

Some Changes in etherpad source for your server…


# cd /usr/local
# cd etherpad/trunk/etherpad
# cp etc/ data/











Database Setup
The scripts assume mysqld is running on localhost. Once mysqld is running, you can set up the etherpad database by running the following command inside ajcode/etherpad/.

# bin/
This will create a database called “etherpad” with the password “password”, and grant privileges to the user “etherpad”.

All the tables will be set up the first time etherpad is run.

EtherPad compiles all its Java and Scala libraries into a single JAR. To build this jar, you can run the following command inside ajcode/etherpad/.

# bin/
If you modify anything in ajcode/infrastructure, you will most likely need to kill the server, rebuild the jar, and re-launch the server before your change takes effect.

Code inside ajcode/etherpad/src can be modified while the server is running, and the changes will automatically get picked up.

To run the etherpad web server, execute the following command inside ajcode/etherpad/.

# bin/
The first time you run this, it should print out lots of messages about database migrations and finally print:

HTTP server listening on http://youdomain:9000/
At this point, you should be able to visit http://youdomain:9000/ in your web browser and create a new pad.

Thanks to Pauleira!

If you have error related to JVM

Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

Fix using

# export _JAVA_OPTIONS=’-Xms32m -Xmx56m -Xss128k -XX:PermSize=32m -XX:MaxPermSize=64m’

Other Link:

AWS CloudFront with PHP

Amazon CloudFront is a web service for content delivery (CDN). It integrates with other Amazon Web Services EC2 / S3 to give developers and businesses an easy way to distribute content to end users with low latency and high data transfer speeds.

Digital Inspiration – Thanks to… it always provides help for all latest technologies 🙂

You can follow basic steps here to setup CloudFront with Amazon S3 with your domain…
How to Setup Amazon S3 with CloudFront as a Content Delivery Network

You can download Cloudfront keys from AWS account


$file="svnlabs.flv"; // file on Amazon S3

function rsa_sha1_sign($policy, $private_key_filename) {
    $signature = "";

    // load the private key
    $fp = fopen($private_key_filename, "r");
    $priv_key = fread($fp, 8192);
    $pkeyid = openssl_get_privatekey($priv_key);

    // compute signature
    openssl_sign($policy, $signature, $pkeyid);

    // free the key from memory

    return $signature;

function url_safe_base64_encode($value) {
    $encoded = base64_encode($value);
    // replace unsafe characters +, = and / with the safe characters -, _ and ~
    return str_replace(
        array('+', '=', '/'),
        array('-', '_', '~'),

function encode_query_params($stream_name) {

    return str_replace(
        array('?', '=', '&'),
        array('%3F', '%3D', '%26'),

/// Download from here...

$private_key_filename = 'pk-XXXXXXXXXXXXXXXXXXXX.pem';
$cloudfront= '';

$file_location = "$cloudfront$file";

$expires = time() + 3;  // 3 min from now
$remote_ip = $_SERVER['REMOTE_ADDR'];

$policy = 
            '"Resource":"'. $file_location . '",'.
                '"IpAddress":{"AWS:SourceIp":"' . $remote_ip . '/32"},'.
                '"DateLessThan":{"AWS:EpochTime":' . $expires . '}'.
    ']' .

$encoded_policy = url_safe_base64_encode($policy);
$signature = rsa_sha1_sign($policy, $private_key_filename);
$encoded_signature = url_safe_base64_encode($signature);

<title>CloudFront Implementation in PHP</title> 
<a href='<?php echo "$file_location$streamer"; ?>'><?php echo "$file_location$streamer"; ?></a> 

A Master inspires you by his being & learning happens. 😉

The best way to consume API



$url = ""; // web service URL 

$client = new nusoap_client($url, false); // soap client to consume API

// XML payload from "soapUI" to send over wsdl server
$xmlRequest='<soapenv:Envelope xmlns:soapenv="" xmlns:tem="" xmlns:hot="">

$return = $client->send($xmlRequest, $url);  // send xml to service url

print_r($return);  // excepted output 😉


Don’t find fault. Find a remedy.

Install geoip on xampp

Geocoding (finding latitude/longitude for street addresses), Geotagging (tagging media with latitude/longitude coordinates), and Geolocation (finding latitude/longitude of computer with IP X-Forwarded-For). There are some options to install on linux environment:

# wget
# gunzip GeoLiteCity.dat.gz
# sudo mkdir -v /usr/share/GeoIP
# sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat


Install geoip with php5
# sudo apt-get install php5-geoip (ubuntu)

# sudo yum install php5-geoip (centOS)

Or Try # yum install geoip-devel

# sudo pecl install geoip (with PECL)

In Windows environment we have to add extension “php_geoip.dll” with PHP

Download extension from here :

Copy “php_geoip.dll” to xampp “php/ext” .. add a line in php.ini
“extension=php_geoip.dll” and restart xampp

Linux: “”

This extension will work on development system using Windows, Apache 2.2.3 and PHP 5.2.10.
We can
check “geoip” with phpinfo() module is loaded.

= geoip_record_by_name('');
if (
$record) {

    [country_code] => US
    [region] => CA
    [city] => Marina...
    [postal_code] =>
    [latitude] => 23.9776792798
    [longitude] => -128.435796741
    [dma_code] => 867
    [area_code] => 400

$result = geoip_record_by_name('');

There is alternative PHP version of the GeoIP API from MaxMind, but this solution is quite slow on servers. MaxMind uses MaxMind database to display geo locations. 

Download youtube videos using PEAR

PEAR have rich library to access web based resources easily…


$sv = new SVTube();
$sv->download(“D7cm-yu-CP0”, “svnlabs.flv”)


Class: SVTube.php


require_once ‘HTTP/Client.php’;
require_once ‘HTTP/Request.php’;

class SVTube {

var $req;
var $debug = false;
var $auth = false;

function download ($video_id, $video_filename) {
$url = “”.$video_id;
$this->req =& new HTTP_Request($url);
$response = $this->req->sendRequest();

if (PEAR::isError($response)) {
echo $response->getMessage().”\n”;
} else {
$page = $this->req->getResponseBody();

preg_match(‘/\&t=([^”]*)”/si’, $page, $match);

$html=html_entity_decode(urldecode(str_replace(‘\x’, ‘%’, $match[1])),ENT_QUOTES, “UTF-8”);

$echo = explode(“&”, $html);

$url = “”.$echo[0].”&fmt=5&asv=3&video_id=”.$video_id;

if ($this->debug)
return $url.”\n”;

$req =& new HTTP_Request($url,array (“allowRedirects”=>true, “maxRedirects”=> 99));
$req->addHeader(“User-Agent”,”Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)”);
$response = $req->sendRequest();


if (PEAR::isError($response)) {
//echo $response->getMessage().”\n”;
return “Error: Failed to open video file on YouTube\n”;
} else {
if ($o = fopen ($video_filename, “w”)) {
fclose ($o);
return “Download complete! File: “.$video_filename.”\n”;
} else {
return “Error: Failed to open video-file\n”;