需求:用户发布文章需要在后台上传一段音频文件,我们要使用php程序获取这段音频文件的播放时长,存放于数据库!解析来我们来看具体的实现方法。
一、下载gitid3这个类库文件(gitId3官网地址:http://www.getid3.org/)

将getid3文件放在thinkphp的extend文件夹
二、编写上传方法
/**
 * @return string
 * @throws Exception
 * File Upload
 */
function upload(){
    $file = request()->file("image");
    //这一步是为了防止php配置文件上传大小限制导致file为nullde 情况
    if(!empty($_FILES) && empty($file)){
        throw new \LogicException('上传文件大小超过配置',10020);
    }
    $info = $file->validate(['size'=>15567998,'ext'=>'jpg,png,gif,jpeg,mp3,wma,wav,ogg,ape,acc'])->move(ROOT_PATH . 'public' . DS . 'uploads');
    if(!$info){
        throw new \Exception($file->getError(),\think\Config::get('error_table.upload')['code']);
    }
    $file_path = $info->getSaveName();
    $extend = $info->getExtension();
    //如果是音频类型的文件我们将调用gitid3类来获取音频播放时长
    if($extend == 'mp3' || $extend == 'wma' ||  $extend == 'wav' || $extend == 'ogg' || $extend == 'ape' || $extend == 'acc'){
        \think\Loader::import('MP3\getid3');//引入get3文件
        $getId3 = new \getID3();
        //打开上面我们上传的文件
        $file_info = $getId3->analyze(ROOT_PATH.'public'.DS.'/uploads/'.$file_path);
        $audio_size = $file_info['playtime_seconds']; //Calculate the duration of the audio
        return [
            'file_path'=>$file_path,
            'audio_size'=>$audio_size //这个就是音频播放时长单位秒
        ];
    }else{
        return [
            'image_path'=>$file_path,
        ];
    }
}
三、调用uplod方法
$upload_info = upload();
四、前端
<form class="form form-horizontal" id="form-rule-add" method="post" action="" enctype="multipart/form-data">
  
   <div class="row cl">
      <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>音频文件:</label>
      <div class="formControls col-xs-8 col-sm-9"> <span class="btn-upload form-group">
            <input class="input-text upload-url" type="text"  id="uploadfile" readonly nullmsg="请上传音频文件!" style="width:200px">
            <a href="javascript:void();" class="btn btn-primary radius upload-btn"><i class="Hui-iconfont"></i> 浏览文件</a>
            <input type="file" name="image"  class="input-file">
         </span> </div>
   </div>
   <?php if(!empty($one['file_path'])){?>
   <div class="row cl">
      <label class="form-label col-xs-4 col-sm-3">原来音频:</label>
      <div class="formControls col-xs-8 col-sm-9">
         <audio src="<?php echo '/uploads/'.$one['file_path']?>" controls="controls">
            您的浏览器不支持音频播放,请切换IE9已上的浏览器.
         </audio>
      </div>
   </div>
   <?php } ?>
   <div class="row cl">
      <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3">
         <input type="hidden" name="id" value="<?php echo $one['id']?>">
         <input class="btn btn-primary radius" type="submit" value="  提交  ">
      </div>
   </div>
</form>
本文连接:http://www.phpbloger.com/article/33 文章都为原创,转载请注明出处!
来自 http://www.phpbloger.com/article/33
