Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

PHP: ffmpeg to work with audio file

Posted on 2008-06-26
2
Medium Priority
?
944 Views
Last Modified: 2011-10-19
hi this is some part of clipshare script

upload.php

i found a site that teach you to convert mp3 format to flv.

Command for ffmpeg to convert:

ffmpeg -y -i myfile.mp3 -f flv -acodec libmp3 -ab 64 -ac 1 myfile.flv

source from : http://heardspace.sulehosting.co.za/?p=5

my problem is how to modify the code to recognize mp3 file being upload and convert it to flv.


if(isset($_GET['rnd_id']))
{
    STemplate::assign('upload_page', 'upload');
        
    $temp_dir = $_REQUEST['temp_dir'];
    $_POST_DATA = getPostData($temp_dir, $_REQUEST['tmp_sid']);
    
    $upload_dir = $_POST_DATA['upload_dir'];
    $upload_file = $_POST_DATA['upfile_0'];
    $upload_file_path = $upload_dir . $upload_file;
    if(!is_file($upload_file_path) || filesize($upload_file_path) < 0)
    {
	$err = 'Failed to upload selected file!';
    }
    
    $upload_file_size = filesize($uploaded_file_path);
    if($err == "")
    {
	$pos = strrpos($upload_file,".");
	$ph = strtolower(substr($upload_file,$pos+1,strlen($upload_file)-$pos));
	$space = round($upload_file_size/(1024*1024));
	if($config['enable_package']=="yes")
	{
	    check_subscriber($space);
	}
	
	//this should never happen
	if(($ph!="3gp" && ph!="mp3" && $ph!="mp4" && $ph!="mov" && $ph!="asf" && $ph!="flv" && $ph!="mpg" && $ph!="avi" && $ph!="mpeg" && $ph!="wmv" && $ph!="rm" && $ph!="dat") || $space>$config[max_video_size])
	    $err = 'Invalid video format or invalid video size!';	
    }
    
    if($err == "")
    {
 
			// ----- Approve Video -----
			if($config['approve'] == 1) {
				$active="active='0'";
				} else {
				$active="active='1'";
				}
			// -------------------------
 
  $v_title = htmlentities(strip_tags($_POST_DATA[field_myvideo_title])); 
  $v_descr = htmlentities(strip_tags($_POST_DATA[field_myvideo_descr])); 
 
  $sql="insert into video set 
    UID=$_SESSION[UID], 
    title='$v_title', 
    description='$v_descr', 
    keyword='$_POST_DATA[field_myvideo_keywords]', 
    channel='0|$_POST_DATA[listch]|0', 
    space = '$space', 
    addtime='".time()."', 
    adddate='".date("Y-m-d")."', 
    vkey='".mt_rand()."', 
    type='$_POST_DATA[field_privacy]',
	$active, 
    filehome='$_POST_DATA[p]'";
 
	$conn->execute($sql);
    	$vid=mysql_insert_id();
        $vdoname=$vid.".".$ph;
	$ff = $config['vdodir'].'/'.$vdoname;
	
	//rename uploaded file
	if(rename($upload_file_path,$ff))
	{
	    //create background conversion process
 
if($config[vresize] == 1) {$encodecommand="$config[mencoder] $config[vdodir]/$vdoname -o $config[flvdodir]/".$vid.".flv -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=$config[vbitrate]:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -vop scale=$config[vresize_x]:$config[vresize_y] -srate $config[sbitrate]";}
else {$encodecommand="$config[mencoder] $config[vdodir]/$vdoname -o $config[flvdodir]/".$vid.".flv -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=$config[vbitrate]:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -srate $config[sbitrate]";}
 
		exec("$config[phppath] $config[BASE_DIR]/convert.php $vdoname $vid $ff> /dev/null &"); 
	    
		//create temporary (video is converting) thumbs	
		video_to_frame2($ff, $vid);
			
		//get duration
		exec("$config[mplayer] -vo null -ao null -frames 0 -identify $config[vdodir]/$vdoname", $p);
    		while(list($k,$v)=each($p))
    		{
        	    if($length=strstr($v,'ID_LENGTH='))
        	    break;
    		}
    		$lx = explode("=",$length);
    		$duration = $lx[1];
 
	} else {
	    $err = 'Failed to rename uploaded file!';
	}
    }
    
    if($err == "")
    {
	$space=get_size($ff);
	$space=round($space/(1024*1024));
	$conn->execute("update video set space='$space' where VID='$vid'");
	$key=substr(md5($vid),11,20);
	send_subscribed_mail($_SESSION[UID],'$key',$_SESSION[EMAIL]);
 
        $sql="update video set
    		vdoname='$vdoname',
                flvdoname='".$vid.".flv',
                duration='$duration',
                vkey='$key' WHERE VID=$vid";
        $conn->execute($sql);
       
 
        if($config['enable_package']=="yes")
        {
    	    $sql = "update subscriber set used_space=used_space+$space, used_bw=used_bw+$space, total_video=total_video+1 where UID=$_SESSION[UID]";
            $conn->execute($sql);
        }
        
        header("Location:$config[baseurl]/upload_success.php?viewkey=$key&upload=yes"); exit;
    }
}

Open in new window

upload.txt
0
Comment
Question by:alicca
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 2

Author Comment

by:alicca
ID: 21877628
its start on line 68 of my quote code

      //create background conversion process
 
if($config[vresize] == 1) {$encodecommand="$config[mencoder] $config[vdodir]/$vdoname -o $config[flvdodir]/".$vid.".flv -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=$config[vbitrate]:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -vop scale=$config[vresize_x]:$config[vresize_y] -srate $config[sbitrate]";}
else {$encodecommand="$config[mencoder] $config[vdodir]/$vdoname -o $config[flvdodir]/".$vid.".flv -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=$config[vbitrate]:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -srate $config[sbitrate]";}


how to get it work?

put

if ($ph=="mp3") {
action
}

something like this?
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 21894933
Alicca:

The general way to upload files goes something like this:

Form input identifies the file to be uploaded (one file at at time)
PHP uploads the file to a temp space
You make a security check to be sure it's really a file that PHP uploaded
You move the file from the temp space to the place where you want it.

In the code snippet, I've put my upload script for pictures (JPGs).  There are some local functions, so some of it will look like pidgin code, but you should be able to follow the logic.

If you look at the function where I resize the images, you will find that you could do your function to convert from MP3 to FLV at the same point in the logic flow.  This occurs near the bottom of the script near the line that says, "RESIZE THE FILE TO FIT PAGE WIDTH"

Hope that helps, ~Ray
<?php // admin_photos.php 
$config_page= getcwd() . '/_config.php'; require_once($config_page);
 
access_control();
if (!admin_access_control()) { die('Admin Error'); }
 
/* ********************************************************************************************* */
/* comment lines will work if GD2 is not installed, but will make poorer images                  */
/*                                                                                               */
// MAKE AN IMAGE INTO THE RIGHT SIZE FOR PAGE DISPLAY
function create_right_size_image($image, $width=720) {
 
	$source = imagecreatefromjpeg("$image");
 
	$imageX = imagesx($source);
	$imageY = imagesy($source);
 
	if ($imageX <= $width) {
return FALSE;
}
	if ($imageX > $width) {
		$tnailX = $width;
		$tnailY = (int) (($tnailX * $imageY) / $imageX );
	} else {
		$tnailX	= $imageX;
		$tnailY = (int) (($tnailX * $imageY) / $imageX );
	}
 
	$target = imagecreatetruecolor($tnailX, $tnailY);
//	$target = imagecreate($tnailX, $tnailY);
	imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
//	imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
 
return $target ;
}
/* ********************************************************************************************* */
 
/* ************************************************************************* */
function copy_file_to_data_base($path_to_file, $caption) {
	global $db_connection, $my_dbt_prefix;
	global $photos;
 
// UNCONDITIONALLY DELETE ANY PREVIOUS INFORMATION ABOUT THIS IMAGE
	$sql	= "SELECT _key, filename FROM {$my_dbt_prefix}_PHOTOS WHERE filename = \"$path_to_file\" ";
	if (!$r	= mysql_query("$sql", $db_connection)) { non_fatal_query_error($sql); }
	while ($row	= mysql_fetch_assoc($r)) {
		$_key		= $row[_key];
		$dsql	= "DELETE FROM {$my_dbt_prefix}_PHOTOS WHERE _key = $_key LIMIT 1";
		if (!$d	= mysql_query("$dsql", $db_connection)) { non_fatal_query_error($dsql); }
	}
 
// WRITE THE INFORMATION INTO THE DATA BASE
	$isql	= "INSERT INTO {$my_dbt_prefix}_PHOTOS () VALUES ()";
	if (!$i	= mysql_query("$isql", $db_connection)) { non_fatal_query_error($isql); die(); }
	$_key	= mysql_insert_id($db_connection);
 
	$usql	= "UPDATE {$my_dbt_prefix}_PHOTOS SET ";
	$usql	.= "filename	= \"$path_to_file\", ";
	$usql	.= "caption		= \"$caption\" ";
	$usql	.= "WHERE _key = $_key LIMIT 1";
 
	$errmsg	= TRUE;
	if (!$u	= mysql_query("$usql", $db_connection)) { $errmsg = non_fatal_query_error($usql); }
return ($errmsg);
}
/* ************************************************************************* */
 
// ESTABLISH THE NAME OF THE PHOTOS DIRECTORY
$photos	= 'photos';
 
$page_title	= "Admin | Upload Photo";
 
 
$errors	= array(
	0=>"<font color=green>Success!</font>",
	1=>"<font color=gold>The uploaded file exceeds the upload_max_filesize directive in php.ini</font>",
	2=>"<font color=gold>The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form</font>",
	3=>"<font color=gold>The uploaded file was only partially uploaded</font>",
	4=>"<font color=gold>No file was uploaded</font>",
	6=>"<font color=gold>Missing a temporary folder</font>",
	7=>"<font color=gold>Cannot write file to disk</font>"
);
 
 
if ( (empty($_GET['p'])) && (empty($_POST['MAX_FILE_SIZE'])) ) {
	top_of_page();
	?>
	<h2>Upload Photos for <?=$image_type?> <?=$image_key?></h2>
 
	<!-- nb:enctype -->
	<form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>&p=1" method="POST">
	<!-- MAX_FILE_SIZE must precede the file input field -->
	<input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
	<!-- Name of input element determines name in $_FILES array -->
	<p>
	Find the photo you want to upload, add a caption, then click the "Upload" button below.
	You control the order of the photos on the web pages by setting the "Sequence" number.
	If you upload four tournament photos you might want to give them numbers like 10, 20, 30, 40.
	With the photos numbered that way, if you wanted to add another between 10 and 20, you could just number it 15.
	</p>
 
	<table cellpadding="1" cellspacing="1" border="0">
	<tr><td align="right"><span class="required">Photo: </span></td> <td><input name="userfile" type="file" size="80" /></td></tr>
	<tr><td align="right"><span class="required">Caption: </span></td><td><input type="text" size="80" name="caption" autocomplete="off" /></td></tr>
	<tr><td align="right"><span class="required">Sequence: </span></td><td>	<input type="text" size="4" name="sequence" autocomplete="off" /> Number between 1 and 999</td></tr>
	<tr><td> </td><td><input type="submit" name="_submit" value="Upload" />
	&nbsp; &nbsp; Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> an existing photo.</td></tr>
	</table>
	</form>
	<p>&nbsp;</p><!-- shim -->
 
 
 
	<h2>Photos for <?=$image_type?> <?=$image_key?></h2>
 
 
<?php 
 
 
} else {
 
	top_of_page();
	echo "<h2>Results: Upload Photos for $image_type $image_key</h2>\n";
	echo "<p>\n";
	
// GET THE CAPTION
	$caption	= mysql_real_escape_string(get_clean_text_string($_POST[caption]), $db_connection);
 
// GET THE SEQUENCE NUMBER
	$seq	= intval(get_clean_numeric_string($_POST[sequence]));
	if ($seq > 999) { $seq = 999; }
	$seq	= str_pad("$seq", 4, '0', STR_PAD_LEFT);
 
// SYNTHESIZE THE NEW FILE NAME
	$f_type	= trim(strtolower(end(explode( '.', basename($_FILES['userfile']['name'] )))));
	$my_new_file	= getcwd() . '/' . $photos . '/' . $image_type .'_'. $image_key .'_'. $seq .'.'. $f_type;
	$my_file		= $photos . '/' . $image_type .'_'. $image_key .'_'. $seq .'.'. $f_type;
 
// MOVE THE FILE INTO THE DIRECTORY
	$overwrite	= $_POST['overwrite'];
	$error_code = $_FILES["userfile"]["error"];
	$file_size	= number_format($_FILES["userfile"]["size"]);
 
	if ($error_code != 0) {
		$error_message = $errors[$error_code];
		echo "<p class=\"required\">Upload Error Code: $error_code: $error_message</p>\n";
		end_of_page('N');
	}
 
 
	if (!file_exists($my_new_file)) {
		if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new_file)) {
			$upload_success = 1;
		} else {
			$upload_success = -1;
		}
	} else { // the file already exists
		echo "<b><i>$my_file</i></b> already exists.\n";
		if (empty($overwrite)) {
			$upload_success = 0;
		} else { // attempt to make a backup
			$now	= date('Y-m-d');
			$my_bak = $my_new_file . '.' . $now . '.bak';
			if (!copy($my_new_file, $my_bak)) {
				echo "<b>Attempted Backup Failed!</b>\n";
			}
			if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new_file)) {
				$upload_success = 2;
			} else {
				$upload_success = -1;
			}
		}
	}
 
	if ($upload_success == 2) { echo "It has been overwritten.\n"; }
	if ($upload_success == 1) { echo "<b><i>$my_file</i></b> has been saved.\n"; }
	if ($upload_success == 0) { echo "<b>It was NOT overwritten.</b>\n"; }
 
	if ($upload_success > 0) {
		echo "$file_size bytes uploaded.\n";
		chmod ($my_new_file, 0755);
		copy_file_to_data_base($my_file, $caption);
	}
 
	echo "</p>\n";
 
// RESIZE THE FILE TO FIT PAGE WIDTH, IF NECESSARY
	if ($upload_success > 0) {
		if ($imageblob	= create_right_size_image($my_new_file)) {
			imagejpeg($imageblob, $my_new_file);
		}
	}
 
	echo "<p><a href=\"$_SERVER[PHP_SELF]?{$get_key}\">Upload Another?</a></p>\n";
 
	if ($image_type == 'A') {
		echo "<p><a href=\"anglers.php?{$get_key}\">Check Angler Page</a></p>\n";
	}
 
	if ($image_type == 'C') {
		echo "<p><a href=\"series.php?{$get_key}\">Check Series Page</a></p>\n";
	}
 
	if ($image_type == 'T') {
		echo "<p><a href=\"results.php?{$get_key}\">Check Results Page</a></p>\n";
	}
 
	end_of_page('N');
}
?>

Open in new window

0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question