Page 1 of 1

Help on Audio class

Posted: Wed Oct 24, 2007 4:48 am
by avijitm
pickle | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Please help! i have downloaded a audio class from phpclass.org, it will generate a weveform. but i can't be able to 
generate long waveform. it will show a fatal error: memory overflowed!  
here is the code:
--------------------------
[syntax="php"]
<?php
/*
// This code taken from WavEdit v.1.20 (Wave File Editor), Author: Thi Dinh (dht@pviet.com), http://www.phpclasses.org //
// I changed it a bit for my custom requirement //
// I sincerely thank Thi Dinh //
*/
/*
	This class creates a WAVEFORM graph representation of an WAV file
	=================================================================
*/
class wavVisualization{

	var $afiles = array();    	// array of file attributes
	var $arrData = array();
	var $wavs = array();
	var $header = "";
	var $imgWidth;
	var $imgHeight;
	var $bgColor;
	var $grpColor;
	var $bdColor;
	var $visual_grid;			// 0|1
	var $gridColor;
	var $visual_border;			// 0|1
	var $imgBorder;
	var	$visual_graph_mode;		// 0|1
	var $visual_fileformat;		// "jpeg","png", everything & else default = "png"
		
	function wavVisualization($ingWid,$imgHei,$imgtype=""){ // Constructor function
		//Clip value
		$this->peakClip8 = 250;
		$this->peakClip16 = 32000;
		
		//Image Config
		$this->font = 3;
		$this->fontaxis = 2;
		$this->numberGrid = 8;
		
		$this->imgWidth = $ingWid;
		$this->imgHeight = $imgHei;
		$this->grpColor = "#0000FF";
		$this->bgColor = "#DDF3DD";
		
		$this->visual_grid = 1;
		$this->gridColor = "#D0D0D0";
		
		$this->bdColor = "#CECEEC";
		$this->titleColor = "#0000FF";
		
		$this->visual_border = 1;
		$this->imgBorder = 1;
		
		$this->visual_graph_mode = 0;
		
		if(empty($imgtype) || $imgtype=="png"){
			$this->visual_fileformat = "png";
		}
		else{
			$this->visual_fileformat = "jpeg";
		}
	}
	
	//== Get File content ==//	
	function loadFile($filenam){
		$this->afiles['name'] = $this->getFileName($filenam);
		$content = file_get_contents($filenam) or die("HALT: Cannot retrieve file " . $filenam . "! Please check again");
		$this->getStructure($content);
		$this->afiles['structure'] = $this->wavs;
		
		$this->getDataArr($this->unpackData($this->wavs['Data']));
		$this->afiles['arrdata']= $this->arrData;
	}
	
	//== Get Wave file Name ==//
	function getFileName($path){
		if(strstr($path,'/') || strstr($path,"\\")){
			$path = str_replace('\\','/', $path);
			$pattern = "/^(.*?)(\/.*?)+(\/.*?)(.wav)$/i";
			if(preg_match($pattern,$path,$matches)){
				return ltrim($matches[3],'/');
			}
			else{
				$name = "wavefile_" . $this->default_name++;
				return $name;
			}
		}
		else{
			$name = str_replace(".wav","",$path);
			return $name;
		}
	}
	
	
	//== Get structure of wav file ==//
	function getStructure($binstr){
		$this->wavs['ChunkID'] = substr($binstr,0,4); //=Return RIFF or MPEG=//
		$this->wavs['ChunkSize'] = $this->unpackHeader(substr($binstr,4,4)); //=Total file size-8 bytes=>(ChunkID+ChunkSize)=//
		$this->wavs['Format'] = substr($binstr,8,4); //=RIFF Type ex WAVE=//
		//==Wave chunks start==//
		$this->wavs['Subchunk1ID'] = substr($binstr,12,4);
		$this->wavs['SubChunk1Size'] = $this->unpackHeader(substr($binstr,16,4));
		$this->wavs['AudioFormat'] = $this->unpackHeader(substr($binstr,20,2));
		$this->wavs['NumChannels'] = $this->unpackHeader(substr($binstr,22,2));
		$this->wavs['SampleRate']  = $this->unpackHeader(substr($binstr,24,4));
		$this->wavs['ByteRate'] = $this->unpackHeader(substr($binstr,28,4));
		$this->wavs['BlockAlign'] = $this->unpackHeader(substr($binstr,32,2));
		$this->wavs['BitsPerSample'] = $this->unpackHeader(substr($binstr,34,2));
		
		//check extra format bytes
		if($this->wavs['SubChunk1Size']==16){
			$this->wavs['Subchunk2ID'] = substr($binstr,36,4);
			$this->wavs['SubChunk2Size'] = $this->unpackHeader(substr($binstr,40,4));
			$this->wavs['Data']= substr($binstr,44,strlen($binstr));
		}
		elseif($this->wavs['SubChunk1Size']==18){
			$this->wavs['ExtraFormatBytes'] = substr($binstr,36,2);
			$this->wavs['Subchunk2ID'] = substr($binstr,38,4);
			$this->wavs['SubChunk2Size'] = $this->unpackHeader(substr($binstr,42,4));
			$this->wavs['Data']= substr($binstr,46,strlen($binstr));
		}
		$this->wavs['NumberSamples']= ($this->wavs['SubChunk2Size']*8)/($this->wavs['NumChannels']*$this->wavs['BitsPerSample']);
	}


	//== Get Decimal Values ==//
	function unpackHeader($str,$opt=""){
		if(strlen($str)>2){
			$arr = unpack("V*",$str);
		}
		else{
			$arr = unpack("v*",$str);
		}
		return $arr[1];
	}
	
	//== unpackData ==//
	function unpackData($strbin){
		$a=fopen('a.txt','w+');
		fwrite($a,$strbin);
		fclose($a);
		//exit();
		$handle = fopen('a.txt', "r");
		$contents = fread($handle, filesize('a.txt'));
		//exit();
		if($this->wavs['BlockAlign']==1){
		//ob_start();
			$xx = unpack("C*",$strbin);	
			//ob_end_flush();
			return $xx;
						//unsign Character
		}
		else{
		$yy = unpack("s*",$contents);	
			return $yy;				//sign int16 //error occuring here//
		}
		fclose($handle);
		
	}
	

	
	//== getArrayData ==//
	function getDataArr($arr){
		//echo("<pre>");
		//print_r($arr);
		//echo("</pre>");
		$this->arrData = array();
		if($this->wavs['NumChannels']==1){
			$this->arrData[0] = $arr;
		}
		else{
			$arrsize = sizeof($arr);
			for($j=1;$j<$arrsize;$j++){
				if($j%2==0){
					$this->arrData[0][] = $arr[$j];
				}
				else{
					$this->arrData[1][] = $arr[$j];
				}
			}
		}
	}
	
	// ************************************************************************
	// longCalc calculates the decimal value of 4 bytes
	// mode = 0 ... b1 is the byte with least value
	// mode = 1 ... b1 is the byte with most value
	// ************************************************************************			

	function longCalc ($b1,$b2,$b3,$b4,$mode)
	{
		$b1 = hexdec(bin2hex($b1));    					
		$b2 = hexdec(bin2hex($b2));    					
		$b3 = hexdec(bin2hex($b3));    					
		$b4 = hexdec(bin2hex($b4));    					
		if ($mode == 0)
		{
			return ($b1 + ($b2*256) + ($b3 * 65536) + ($b4 * 16777216));	
		} else {
			return ($b4 + ($b3*256) + ($b2 * 65536) + ($b1 * 16777216));
		}
	}

	// ************************************************************************
	// shortCalc calculates the decimal value of 2 bytes
	// mode = 0 ... b1 is the byte with least value
	// mode = 1 ... b1 is the byte with most value
	// ************************************************************************			

	function shortCalc ($b1,$b2,$mode)
	{
		$b1 = hexdec(bin2hex($b1));    					
		$b2 = hexdec(bin2hex($b2));    					
		if ($mode == 0)
		{
			return ($b1 + ($b2*256));	
		} else {
			return ($b2 + ($b1*256));
		}
	}
	
	//=============== Draw Wave Image===============//
	
	function drawImgWave($val="",$outputdir=""){
		if(empty($val)){
			$fname = $this->afiles['name'];
		}
		else{
			$fname = $this->afiles['name'] . "_" . $val;
		}
		$this->doDrawImg($fname,$outputdir);
	}
	
	function doDrawImg($output,$outputdir){
		$arr = $this->arrData;
		$bytes_per_pixel = floor($this->wavs['NumberSamples']/$this->imgWidth);
		$visualData = array();
			
		for($c=0;$c<$this->wavs['NumChannels'];$c++){
			$dataindex = 1;
			$currentindex= 1;
			while($currentindex<sizeof($arr[0])){
				//$loopindex= 0;
				$visualData[$c][$dataindex] = ($this->wavs['BlockAlign']==1)? $arr[$c][$currentindex]:($arr[$c][$currentindex]+32768);
					
				$currentindex+= $bytes_per_pixel;
				$dataindex++;
			}
		}
		
		$imgHeight = $this->imgHeight*$this->wavs['NumChannels'];
		$im = imagecreate ($this->imgWidth, $imgHeight+20) or die ("Cannot Initialize new GD image stream!");
		
		$background_color = imagecolorallocate ($im, hexdec(substr($this->bgColor,1,2)),hexdec(substr($this->bgColor,3,2)),hexdec(substr($this->bgColor,5,2)));
		$bground = imagecolorallocate ($im, hexdec(substr($this->bgColor,1,2)),hexdec(substr($this->bgColor,3,2)),hexdec(substr($this->bgColor,5,2)));
		$graph = imagecolorallocate ($im, hexdec(substr($this->grpColor,1,2)),hexdec(substr($this->grpColor,3,2)),hexdec(substr($this->grpColor,5,2)));
		$border = imagecolorallocate ($im, hexdec(substr($this->bdColor,1,2)),hexdec(substr($this->bdColor,3,2)),hexdec(substr($this->bdColor,5,2)));
		$grid = imagecolorallocate ($im, hexdec(substr($this->gridColor,1,2)),hexdec(substr($this->gridColor,3,2)),hexdec(substr($this->gridColor,5,2)));
		$titlecolor = imagecolorallocate ($im, hexdec(substr($this->titleColor,1,2)),hexdec(substr($this->titleColor,3,2)),hexdec(substr($this->titleColor,5,2)));
		
		if($this->imgBorder){
			//Main image border
			imagerectangle ($im,0,0,($this->imgWidth-1),($imgHeight-1+20),$border);
			//X-axis legend
			imageline ($im,0,($imgHeight-1),($this->imgWidth-1),($imgHeight-1),$border);
		}

		//Draw Text 
		$title = "";
		//$title = $output . ".wav";
		$x = ($this->imgWidth - floor(strlen($title))*imagefontwidth($this->font) )/2;
		$y = 2;
		imagestring($im,$this->font,$x,$y,$title,$titlecolor);
		//======================//
		
		//Draw Grid
		$numbergrid = $this->numberGrid;
		$pixel_per_grid = sizeof($visualData[0])/$numbergrid;
		for($i=1;$i<$numbergrid;$i++){
			$gx = $pixel_per_grid*$i;
			ImageLine($im,$gx,0,$gx,$imgHeight,$grid);
			
			//draw axis legend
			$xaxis = $gx*$bytes_per_pixel;
			if($xaxis<sizeof($this->arrData[0])){
				$xtime = floor($xaxis*1000/$this->wavs['SampleRate']);
				$xtext = $xtime . "ms";
				if($xtime>1000){
					$xtext = round($xtext/1000,2) . "s";
				}
			}
			$xpos = $gx - floor(strlen($xtime))*imagefontwidth($this->fontaxis)/2;
			imagestring($im,$this->fontaxis,$xpos,($imgHeight+5),$xtext,$titlecolor);		
		}

		// this for-loop draws a graph for every channel	
		$middle = ($this->wavs['BlockAlign']==1)? 128 : 32768;
		$height_channel = $imgHeight/$this->wavs['NumChannels'];
		for($c=0;$c<$this->wavs['NumChannels'];$c++){
			$factor = $imgHeight/($middle*2*$this->wavs['NumChannels']);		
			$last_x = 1;
			$last_y = (2*$c+1)*($imgHeight)/(2*$this->wavs['NumChannels']);

			for($i=1;$i<$this->imgWidth;$i++){
				$val = ($visualData[$c][$i]*$factor)+($c*$height_channel);
				
				if($this->visual_graph_mode == 0){
					ImageLine ($im,$last_x,$last_y,$i,$val,$graph);
				}
				else{
					ImageLine ($im,$i,($height_channel),$i,$val,$graph);
				}
				$last_x = $i;
				$last_y = $val;
			}
		}
		
		//=Output to png or jpg format=//
		if (strtolower($this->visual_fileformat) == "jpeg"){	
			$imgName = $outputdir.$output . ".jpg";					
			imagejpeg ($im,$imgName);
		} 
		else {
			$imgName = $outputdir.$output . ".png";
			imagepng ($im,$imgName);					
		}
		chmod($imgName,0777);
		imagedestroy($im);
	}
	
	function viewImage($val=""){
		if (strtolower($this->visual_fileformat) == "jpeg"){
			$extn=".jpg";
		} 
		else {
			$extn=".png";
		}
		$fname = (empty($val)) ? $this->afiles['name'] . $extn : $this->afiles['name']."_".$val.$extn;
		return($fname);
	}
	
}
?>
---------------------------------
and this is my implementation. please help me!!!!!!!!!!!!


pickle | Please use[/syntax]

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Wed Oct 24, 2007 9:52 am
by pickle
Sounds like you're running out of memory. Look into ini_set().

Posted: Wed Oct 24, 2007 12:38 pm
by feyd
... or start dumping memory you don't need anymore .. in some fashion.