MP3 waveforms with PHP


Hits: 7099  

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

soundcloud-waveform

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

wavesurfer.js

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wavesurfer.js/1.4.0/wavesurfer.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wavesurfer.js/1.4.0/plugin/wavesurfer.playlist.min.js"></script>

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

<script>

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


wavesurfer.load([MP3-File-URL]);

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

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

</script>

WaveForm generated using SOX

WaveForm Generator using SOX

Links:

https://github.com/afreiday/php-waveform-png
https://github.com/afreiday/php-waveform-svg
https://github.com/beschulz/wav2png
https://github.com/beschulz/wav2json
http://www.rarewares.org/mp3-lame-bundle.php

Create Website Thumbnails using PhantomJS


Hits: 9408  

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 = ‘http://www.svnlabs.com/’;
page.open(url, function (status) {
//Page is loaded!
phantom.exit();
});

Features:

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

Fork on Github https://github.com/ariya/phantomjs

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.

URL2PNG-URL2PDF-HTML2JPG-URL2IMAGE
URL2PNG-URL2PDF-HTML2JPG-URL2IMAGE
// Thumbnail of Webpage using webthumb.js

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

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

Download webthumb.js

# phantomjs webthumb.js http://www.svnlabs.com svnlabs.png
# phantomjs webthumb.js http://www.svnlabs.com svnlabs.pdf

You can even capture webpage as good quality PDF file 😉

Output:

svnlabs.png
svnlabs.pdf

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

# phantomjs examples/rasterize.js http://www.svnlabs.com/ svnlabs.png
# phantomjs examples/rasterize.js ‘http://www.svnlabs.com/’ 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


Hits: 2607  

Connect the World of Sound

* Share : http://developers.soundcloud.com/blog/sharing-sounds
* Stream : http://developers.soundcloud.com/blog/stream-and-download
* Customize : http://developers.soundcloud.com/blog/custom-players

SoundCloud Widgets

http://soundcloud.com/pages/widgets

http://soundcloud.com/svnlabs

API | Javascript SDK | Widget | Custom Player | oEmbed

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

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

?>

Demo Apps

https://github.com/mptre/ci-soundcloud
https://github.com/jazonv/soundclouder
https://github.com/fastfrwrd/joshuashank.com
https://github.com/thegreat/Drupal-SoundCloud
https://github.com/idflood/sndlite

There are many sound applications built using the SoundCloud API.

Install Etherpad on SUSE Linux


Hits: 4898  

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
http://www.cyberciti.biz/faq/linux-how-to-find-if-processor-is-64-bit-or-not/

# cd /usr/local

Requirements
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 http://autosetup1.googlecode.com/files/jdk-6u20-linux-i586-rpm.bin
# sh jdk-6u20-linux-i586-rpm.bin

# java -version

Install fastjar

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

Download Scala

# wget http://www.scala-lang.org/sites/default/files/linuxsoft_archives/downloads/distrib/files/scala-2.7.7.final.tgz
# tar xvzf scala-2.7.7.final.tgz

Install MySQL

http://dev.mysql.com/downloads/mysql/5.1.html#downloads

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

Download MySQL Java Connector

Try

# zypper install mysql-connector-java

Or

# wget http://mysql.llarian.net/Downloads/Connector-J/mysql-connector-java-5.1.18.tar.gz
# 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

Environment
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/scala-2.7.7.final/
export SCALA=$SCALA_HOME/bin/scala
export PATH=$JAVA_HOME/bin:$SCALA_HOME/bin:$PATH
export MYSQL_CONNECTOR_JAR=/usr/local/mysqlconnector/mysql-connector-java-5.1.18-bin.jar

# cat myENV >> /etc/profile

Download EtherPad

# hg clone https://etherpad.googlecode.com/hg/ etherpad

Some Changes in etherpad source for your server…

./etc/etherpad.localdev-default.properties

# cd /usr/local
# cd etherpad/trunk/etherpad
# cp etc/etherpad.localdev-default.properties data/etherpad.local.properties

./bin/setup-mysql-db.sh

./src/main.js

./src/templates/pro/admin/admin-template.ejs

./src/templates/framed/framedheader-pro.ejs

./src/static/crossdomain.xml

./src/etherpad/pro/pro_utils.js

./src/etherpad/globals.js

./src/etherpad/control/pro/pro_main_control.js

./src/etherpad/control/pad/pad_control.js

./src/etherpad/control/global_pro_account_control.js

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/setup-mysql-db.sh
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.

Compiling
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/rebuildjar.sh
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.

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

# bin/run-local.sh
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:
http://code.google.com/p/etherpad/
http://etherpad.com/
https://github.com/ether/pad
http://etherpad.org/

AWS CloudFront with PHP


Hits: 9130  

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.

http://aws.amazon.com/cloudfront/

Digital Inspiration – Thanks to http://www.labnol.org… 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
https://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key

<?php
 
error_reporting(E_ALL);

$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);
    fclose($fp);
    $pkeyid = openssl_get_privatekey($priv_key);

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

    // free the key from memory
    openssl_free_key($pkeyid);

    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('-', '_', '~'),
        $encoded); 
}



function encode_query_params($stream_name) {

    return str_replace(
        array('?', '=', '&'),
        array('%3F', '%3D', '%26'),
        $stream_name);
}


/// Download from here... https://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key

$private_key_filename = 'pk-XXXXXXXXXXXXXXXXXXXX.pem';
$key_pair_id = 'XXXXXXXXXXXXXXXXXXXX';
$cloudfront= 'http://svnlabs.cloudfront.net/';

$file_location = "$cloudfront$file";

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

$policy = 
'{'.
    '"Statement":['.
        '{'.
            '"Resource":"'. $file_location . '",'.
            '"Condition":{'.
                '"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);
$streamer="?Policy=$encoded_policy&Signature=$encoded_signature&Key-Pair-Id=$key_pair_id" 

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

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

The best way to consume API


Hits: 4737  
 
SOAP UI
 
<?php

require_once('lib/nusoap.php');

$url = "http://www.hotelscombined.com/api/wsdl/SearchSoap.wsdl"; // 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="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:hot="http://schemas.datacontract.org/2004/07/HotelsCombined.WebServices.Version4">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:HotelSearch>
         <!--Optional:-->
         <tem:request>
            <hot:ApiKey>?</hot:ApiKey>
            <hot:Checkin>?</hot:Checkin>
            <hot:Checkout>?</hot:Checkout>
            <hot:DisplayCurrency>?</hot:DisplayCurrency>
            <hot:Guests>?</hot:Guests>
            <hot:HotelID>?</hot:HotelID>
            <hot:LanguageCode>?</hot:LanguageCode>
            <hot:Rooms>?</hot:Rooms>
            <hot:TimeOutInSeconds>?</hot:TimeOutInSeconds>
            <hot:UserAgent>?</hot:UserAgent>
            <hot:UserID>?</hot:UserID>
            <hot:UserIPAddress>?</hot:UserIPAddress>
         </tem:request>
      </tem:HotelSearch>
   </soapenv:Body>
</soapenv:Envelope>';

$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


Hits: 10554  

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 http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
# gunzip GeoLiteCity.dat.gz
# sudo mkdir -v /usr/share/GeoIP
# sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat

geoIP-Dat-Files

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 : http://blog.svnlabs.com/php-5.2.1_geoip-w32.zip

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

Linux: “extension=geoip.so”

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.

<?php
$record
= geoip_record_by_name('www.svnlabs.com');
if (
$record) {
print_r($record);
}
?>

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

<?php
$result = geoip_record_by_name('78.aaa.yyy.xxx');
var_dump($result);
?>

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


Hits: 2119  

PEAR have rich library to access web based resources easily…

<?php

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

?>

Class: SVTube.php
——————————

<?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 = “http://www.youtube.com/watch?v=”.$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 = “http://www.youtube.com/get_video?el=detailpage&t=”.$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->setMethod(HTTP_REQUEST_METHOD_GET);
$req->addHeader(“User-Agent”,”Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)”);
$response = $req->sendRequest();

$req->getResponseBody();

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”)) {
fwrite($o,$req->getResponseBody());
fclose ($o);
return “Download complete! File: “.$video_filename.”\n”;
} else {
return “Error: Failed to open video-file\n”;
}
}

}
}

}
?>