微信小程序_(校園視)開發視頻的展現頁_上

  

  

 

  微信小程序_(校園視)  開發用戶註冊登錄  傳送門 html

  微信小程序_(校園視)  開發上傳視頻業務  傳送門 前端

  微信小程序_(校園視)  開發視頻的展現頁-上  傳送門 java

  微信小程序_(校園視)  開發視頻的展現頁-下  傳送門 git

 

 

 

小程序首頁視頻列表開發github

  校園視小程序首頁index將分別展現用戶視頻、用戶頭像、用戶名字web

 

const app = getApp()

Page({
  data: {
    // 用於分頁的屬性
    screenWidth: 350
  },

  onLoad: function (params) {
    var me = this;
    var screenWidth = wx.getSystemInfoSync().screenWidth;

    me.setData({
      screenWidth: screenWidth,
    });
  }
})
index.js

 

  <!-- <view wx:for="{{videoList}}" class="item-container">   -->



     <view style='width:{{screenWidth}}px;height:210px;' class='back-img'> 
        <image src="http://localhost:8081/190502AYNKPFRDD4/video/wx70d559ac5d37dd78.o6zAJs59F12Wz0jOMOX2L2uFIE_w.9StRAIr1vMWvc4e5d48a6fc4fabc84946439cb0983d0.jpg" style='width:{{screenWidth}}px;height:210px;' mode="aspectFit" bindtap='showVideoInfo' data-arrindex='{{index}}'></image>
     </view> 


    <view class="desc">
        <view class="faceName">
            <image class='myface' src="http://localhost:8081/190502AYNKPFRDD4/face/wx70d559ac5d37dd78.o6zAJs59F12Wz0jOMOX2L2uFIE_w.9WbWU2SnvtxFf1492da78d683e04183d3f63cc46dde9.png"></image>
            <view class="nickname">Gary</view>
        </view>
    </view>


  <!-- </view>   -->
index.wxml

 

.item-container {
    position: relative;
}

.cover {
    width: 100%;
    height: 400rpx;
    display: block; 
}

.back-img{
    display: block; 
    background-color: black;
}

.desc {
    margin-top: -40rpx;
    margin-bottom: 10rpx;
    display: flex;
    align-items: center;
}

.desc .right {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.desc .faceName {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    margin-left: 10px;
}

.title {
    font-size: 30rpx;
    margin-top: 10rpx;
    margin-left: 20rpx;
    width: 600rpx;
}

.myface {
    display: block;
    width: 60rpx;
    height: 60rpx;
    border-radius: 30rpx;
    margin-top: 10rpx;
    margin-right: 20rpx;
}

.nickname {
    font-size: 20rpx;
    margin-top: 6rpx;
    margin-right: 20rpx;
    color: darkgray;
}
index.wxss

 

 

編寫自定義mapperspring

   添加VideosVO.java實體層數據庫

package com.imooc.pojp.vo;

import java.util.Date;
import javax.persistence.*;

public class VideosVO {

    private String id;
    private String userId;
    private String audioId;
    private String videoDesc;
    private String videoPath;
    private Float videoSeconds;
    private Integer videoWidth;
    private Integer videoHeight;
    private String coverPath;
    private Long likeCounts;
    private Integer status;
    private Date createTime;
    private String faceImage;
    private String nickname;
    
    public String getFace_image() {
          return faceImage;
      }

      public void setFace_image(String faceImage) {
          this.faceImage = faceImage;
      }

      public String getNickname() {
          return nickname;
      }

      public void setNickname(String nickname) {
          this.nickname = nickname;
      }

    public String getId() {
        return id;
    }

    /**
     * @param id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return user_id
     */
    public String getUserId() {
        return userId;
    }

    /**
     * @param userId
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * @return audio_id
     */
    public String getAudioId() {
        return audioId;
    }

    /**
     * @param audioId
     */
    public void setAudioId(String audioId) {
        this.audioId = audioId;
    }

    /**
     * @return video_desc
     */
    public String getVideoDesc() {
        return videoDesc;
    }

    /**
     * @param videoDesc
     */
    public void setVideoDesc(String videoDesc) {
        this.videoDesc = videoDesc;
    }

    /**
     * @return video_path
     */
    public String getVideoPath() {
        return videoPath;
    }

    /**
     * @param videoPath
     */
    public void setVideoPath(String videoPath) {
        this.videoPath = videoPath;
    }

    /**
     * @return video_seconds
     */
    public Float getVideoSeconds() {
        return videoSeconds;
    }

    /**
     * @param videoSeconds
     */
    public void setVideoSeconds(Float videoSeconds) {
        this.videoSeconds = videoSeconds;
    }

    /**
     * @return video_width
     */
    public Integer getVideoWidth() {
        return videoWidth;
    }

    /**
     * @param videoWidth
     */
    public void setVideoWidth(Integer videoWidth) {
        this.videoWidth = videoWidth;
    }

    /**
     * @return video_height
     */
    public Integer getVideoHeight() {
        return videoHeight;
    }

    /**
     * @param videoHeight
     */
    public void setVideoHeight(Integer videoHeight) {
        this.videoHeight = videoHeight;
    }

    /**
     * @return cover_path
     */
    public String getCoverPath() {
        return coverPath;
    }

    /**
     * @param coverPath
     */
    public void setCoverPath(String coverPath) {
        this.coverPath = coverPath;
    }

    /**
     * @return like_counts
     */
    public Long getLikeCounts() {
        return likeCounts;
    }

    /**
     * @param likeCounts
     */
    public void setLikeCounts(Long likeCounts) {
        this.likeCounts = likeCounts;
    }

    /**
     * @return status
     */
    public Integer getStatus() {
        return status;
    }

    /**
     * @param status
     */
    public void setStatus(Integer status) {
        this.status = status;
    }

    /**
     * @return create_time
     */
    public Date getCreateTime() {
        return createTime;
    }

    /**
     * @param createTime
     */
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}
VideosVO.java

 

  在VideosMapperCustom.java層中添加數據庫查詢方法apache

public interface VideosMapperCustom extends MyMapper<Videos> {
    
    public List<VideosVO> queryAllVideos();
    
}
package com.imooc.mapper;

import java.util.List;

import com.imooc.pojo.Videos;
import com.imooc.pojp.vo.VideosVO;
import com.imooc.utils.MyMapper;

public interface VideosMapperCustom extends MyMapper<Videos> {
    
    public List<VideosVO> queryAllVideos();
    
}
VideosMapperCustom.java

 

  在VideosMapperCustom.xml中添加映射以及數據庫查詢語句json

<resultMap id="BaseResultMap" type="com.imooc.pojo.vo.VideosVO" >
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="user_id" property="userId" jdbcType="VARCHAR" />
    <result column="audio_id" property="audioId" jdbcType="VARCHAR" />
    <result column="video_desc" property="videoDesc" jdbcType="VARCHAR" />
    <result column="video_path" property="videoPath" jdbcType="VARCHAR" />
    <result column="video_seconds" property="videoSeconds" jdbcType="REAL" />
    <result column="video_width" property="videoWidth" jdbcType="INTEGER" />
    <result column="video_height" property="videoHeight" jdbcType="INTEGER" />
    <result column="cover_path" property="coverPath" jdbcType="VARCHAR" />
    <result column="like_counts" property="likeCounts" jdbcType="BIGINT" />
    <result column="status" property="status" jdbcType="INTEGER" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    
    <result column="face_image" property="faceImage" jdbcType="VARCHAR" />
    <result column="nickname" property="nickname" jdbcType="VARCHAR" />  
  </resultMap>

 

  <select id="queryAllVideos" resultMap="BaseResultMap">
  
      select v.*,u.face_image as face_image,u.nickname as nickname from videos v
      left join users u on u.id = v.user_id
      where
          1 =1
          and v.status = 1
      order by v.create_time desc
  
  </select>

 

 

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.imooc.mapper.VideosMapperCustom" >
  <resultMap id="BaseResultMap" type="com.imooc.pojo.vo.VideosVO" >
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="user_id" property="userId" jdbcType="VARCHAR" />
    <result column="audio_id" property="audioId" jdbcType="VARCHAR" />
    <result column="video_desc" property="videoDesc" jdbcType="VARCHAR" />
    <result column="video_path" property="videoPath" jdbcType="VARCHAR" />
    <result column="video_seconds" property="videoSeconds" jdbcType="REAL" />
    <result column="video_width" property="videoWidth" jdbcType="INTEGER" />
    <result column="video_height" property="videoHeight" jdbcType="INTEGER" />
    <result column="cover_path" property="coverPath" jdbcType="VARCHAR" />
    <result column="like_counts" property="likeCounts" jdbcType="BIGINT" />
    <result column="status" property="status" jdbcType="INTEGER" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    
    <result column="face_image" property="faceImage" jdbcType="VARCHAR" />
    <result column="nickname" property="nickname" jdbcType="VARCHAR" />  
  </resultMap>
  
  <select id="queryAllVideos" resultMap="BaseResultMap">
  
      select v.*,u.face_image as face_image,u.nickname as nickname from videos v
      left join users u on u.id = v.user_id
      where
          1 =1
          and v.status = 1
      order by v.create_time desc
  
  </select>
  
</mapper>
VideosMapperCustom.xml

 

 

視頻列表分頁查詢接口

   Pagehelper作視頻的分頁

package com.imooc.utils;

import java.util.List;

/**
 * @Description: 封裝分頁後的數據格式
 */
public class PagedResult {
    
    private int page;            // 當前頁數
    private int total;            // 總頁數    
    private long records;        // 總記錄數
    private List<?> rows;        // 每行顯示的內容
    
    public int getPage() {
        return page;
    }
    public void setPage(int page) {
        this.page = page;
    }
    public int getTotal() {
        return total;
    }
    public void setTotal(int total) {
        this.total = total;
    }
    public long getRecords() {
        return records;
    }
    public void setRecords(long records) {
        this.records = records;
    }
    public List<?> getRows() {
        return rows;
    }
    public void setRows(List<?> rows) {
        this.rows = rows;
    }

}
PagedResult.java

 

  查詢視頻的VideoServiceImpl.java中getAllVideos(Integer page, Integer pageSize)方法

@Override
    public PagedResult getAllVideos(Integer page, Integer pageSize) {
        
        PageHelper.startPage(page,pageSize);
        List<VideosVO> list= videosMapperCustom.queryAllVideos();
        
        PageInfo<VideosVO> pageList = new PageInfo<>(list);
        
        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(page);
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(list);
        pagedResult.setRecords(pageList.getTotal());
        
        
        return pagedResult;
    }

 

  在VideoController.java中添加查詢視頻的方法

@PostMapping(value="/showAll")
    public IMoocJSONResult showAll(Integer page) throws Exception {
        
        if(page == null) {
            page = 1;
        }
        
        
        PagedResult result = videoService.getAllVideos(page,PAGE_SIZE);
        return IMoocJSONResult.ok(result);
        
    }

 

package com.imooc.server.impl;

import java.util.List;

import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.mapper.BgmMapper;
import com.imooc.mapper.UsersMapper;
import com.imooc.mapper.VideosMapper;
import com.imooc.mapper.VideosMapperCustom;
import com.imooc.pojo.Bgm;
import com.imooc.pojo.Users;
import com.imooc.pojo.Videos;
import com.imooc.pojp.vo.VideosVO;
import com.imooc.service.BgmService;
import com.imooc.service.UserService;
import com.imooc.service.VideoService;
import com.imooc.utils.PagedResult;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideosMapper videosMapper;
    
    @Autowired
    private VideosMapperCustom  videosMapperCustom;
    
    @Autowired
    private Sid sid;
    

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public String saveVideo(Videos video) {
        
        String id = sid.nextShort();
        video.setId(id);
        
        videosMapper.insertSelective(video);
        
        return id;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void updateVideo(String videoId, String coverPath) {
        
        Videos video = new Videos();
        video.setId(videoId);
        video.setCoverPath(coverPath);
        videosMapper.updateByPrimaryKeySelective(video);
        
    }

    @Override
    public PagedResult getAllVideos(Integer page, Integer pageSize) {
        
        PageHelper.startPage(page,pageSize);
        List<VideosVO> list= videosMapperCustom.queryAllVideos();
        
        PageInfo<VideosVO> pageList = new PageInfo<>(list);
        
        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(page);
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(list);
        pagedResult.setRecords(pageList.getTotal());
        
        
        return pagedResult;
    }


    
}
VideoServiceImpl.java

 

package com.imooc.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.imooc.enums.VideoStatusEnum;
import com.imooc.pojo.Bgm;
import com.imooc.pojo.Users;
import com.imooc.pojo.Videos;
import com.imooc.service.BgmService;
import com.imooc.service.VideoService;
import com.imooc.utils.FetchVideoCover;
import com.imooc.utils.IMoocJSONResult;
import com.imooc.utils.MergeVideoMp3;
import com.imooc.utils.PagedResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


@RestController
@Api(value="視頻相關業務的接口",tags= {"視頻相關業務的controller"})
@RequestMapping("/video")
public class VideoController extends BasicController{
    
    @Autowired
    private BgmService bgmService;
    
    @Autowired
    private VideoService videoService;
    
    
    @ApiOperation(value="上傳視頻", notes="上傳視頻的接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name="userId",value="用戶id",required=true,
                dataType="String" ,paramType="form"),
        @ApiImplicitParam(name="bgmId",value="背景音樂id",required=false,
                dataType="String" ,paramType="form"),
        @ApiImplicitParam(name="videoSeconds",value="背景音樂播放長度",required=true,
                dataType="String" ,paramType="form"),
        @ApiImplicitParam(name="videoWidth",value="視頻的寬度",required=true,
                dataType="String" ,paramType="form"),
        @ApiImplicitParam(name="videoHeight",value="視頻的高度",required=true,
                dataType="String" ,paramType="form"),
        @ApiImplicitParam(name="desc",value="視頻的描述",required=false,
                dataType="String" ,paramType="form")
    })
    @PostMapping(value="/upload",headers="content-type=multipart/form-data")
    public IMoocJSONResult uploadFace(String userId,
            String bgmId,double videoSeconds,int videoWidth,int videoHeight,String desc,
            @ApiParam(value="短視頻",required=true)
            MultipartFile file) throws Exception {
        
            if(StringUtils.isBlank(userId)) {
                return IMoocJSONResult.errorMsg("用戶id不能爲空...");
            }
        
            //文件保存命名空間
            //String fileSpace = "F:/imooc-video-gary";
            //保存到數據庫中的相對路徑
            String uploadPathDB = "/" + userId + "/video";
            String coverPathDB = "/" + userId + "/video";
            
            FileOutputStream fileOutputStream = null;
            InputStream inputStream = null;
            String finalVideoPath = "";
            try {
                if( file != null ) {

                    String fileName = file.getOriginalFilename();
                    //Gary.mp4  使用spilt進行分割
                    String fileNamePrefix = fileName.split("\\.")[0];
                    
                    
                    
                    if(StringUtils.isNoneBlank(fileName)) {
                        //文件上傳的最終保存路徑
                        
                        finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName;
                        //設置數據庫保存的路徑
                        uploadPathDB += ("/" + fileName);
                        coverPathDB = coverPathDB + "/" + fileNamePrefix + ".jpg";
                        
                        File outFile = new File(finalVideoPath);
                        if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
                            //建立父文件夾
                            outFile.getParentFile().mkdirs();
                        }
                        
                        fileOutputStream = new FileOutputStream(outFile);
                        inputStream = file.getInputStream();
                        IOUtils.copy(inputStream, fileOutputStream);
                    }
                    
                }else {
                    return IMoocJSONResult.errorMsg("上傳出錯...");
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return IMoocJSONResult.errorMsg("上傳出錯...");
            }finally {
                if(fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            }
            
            //判斷bgmId是否爲空,
            //若是不爲空,那就查詢bgm的信息,而且合併視頻生成新的視頻
            
            if(StringUtils.isNotBlank(bgmId)) {
                Bgm bgm = bgmService.queryBgmById(bgmId);
                String mp3InputPath = FILE_SPACE + bgm.getPath();
                //System.out.println("1:mp3InputPath + "+mp3InputPath);
                MergeVideoMp3 tool = new MergeVideoMp3(FFMPEG_EXE);
                String videoInputPath = finalVideoPath;
                
                String videdoOutputName = UUID.randomUUID().toString() + ".mp4";
                uploadPathDB = "/" + userId + "/video" + "/" +videdoOutputName;
                finalVideoPath = FILE_SPACE + uploadPathDB;
                tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
                
            }
            
            //對視頻封面進行截圖
            FetchVideoCover videoInfo = new FetchVideoCover(FFMPEG_EXE);
            videoInfo.getCover(finalVideoPath,FILE_SPACE + coverPathDB);
            
            //保存視頻信息到數據庫
            Videos video = new Videos();
            video.setAudioId(bgmId);
            video.setUserId(userId);
            video.setVideoSeconds((float)videoSeconds);
            video.setVideoHeight(videoHeight);
            video.setVideoWidth(videoWidth);
            video.setVideoDesc(desc);
            video.setVideoPath(uploadPathDB);
            video.setCoverPath(coverPathDB);
            video.setStatus(VideoStatusEnum.SUCCESS.value);
            video.setCreateTime(new Date());
            
            String videoId = videoService.saveVideo(video);
            
            return IMoocJSONResult.ok(videoId);
    }
    
    @ApiOperation(value="上傳封面", notes="上傳封面的接口")
    @ApiImplicitParams({        
        @ApiImplicitParam(name="userId",value="用戶id",required=true,
                dataType="String" ,paramType="form"),
        @ApiImplicitParam(name="videoId",value="視頻主鍵id",required=true,
                dataType="String" ,paramType="form")
    })
    @PostMapping(value="/uploadCover",headers="content-type=multipart/form-data")
    public IMoocJSONResult uploadCover(String userId,String videoId, 
            @ApiParam(value="視頻封面",required=true)
            MultipartFile file) throws Exception {
        
            if(StringUtils.isBlank(userId) ||StringUtils.isBlank(videoId) ) {
                return IMoocJSONResult.errorMsg("視頻主鍵id和用戶id不能爲空...");
            }
        
            //文件保存命名空間
            //String fileSpace = "F:/imooc-video-gary";
            //保存到數據庫中的相對路徑
            String uploadPathDB = "/" + userId + "/video";
            
            FileOutputStream fileOutputStream = null;
            InputStream inputStream = null;
            String finalCoverPath = "";
            try {
                if( file != null ) {

                    
                    String fileName = file.getOriginalFilename();
                    if(StringUtils.isNoneBlank(fileName)) {
                        //文件上傳的最終保存路徑
                        
                        finalCoverPath = FILE_SPACE + uploadPathDB + "/" + fileName;
                        //設置數據庫保存的路徑
                        uploadPathDB += ("/" + fileName);
                        
                        File outFile = new File(finalCoverPath);
                        if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
                            //建立父文件夾
                            outFile.getParentFile().mkdirs();
                        }
                        
                        fileOutputStream = new FileOutputStream(outFile);
                        inputStream = file.getInputStream();
                        IOUtils.copy(inputStream, fileOutputStream);
                    }
                    
                }else {
                    return IMoocJSONResult.errorMsg("上傳出錯...");
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return IMoocJSONResult.errorMsg("上傳出錯...");
            }finally {
                if(fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            }
            
            videoService.updateVideo(videoId, uploadPathDB);
            
            return IMoocJSONResult.ok();
    }
    
    
    
    
    @PostMapping(value="/showAll")
    public IMoocJSONResult showAll(Integer page) throws Exception {
        
        if(page == null) {
            page = 1;
        }
        
        
        PagedResult result = videoService.getAllVideos(page,PAGE_SIZE);
        return IMoocJSONResult.ok(result);
        
    }
    
    
}
VideoController.java

 

 

小程序端口的聯調

   經過小程序端拿到index頁面中分頁數目

onLoad: function (params) {
    var me = this;
    var screenWidth = wx.getSystemInfoSync().screenWidth;

    me.setData({
      screenWidth: screenWidth,
    });

    //獲取當前的分頁數
    var page = me.data.page;
    var serverUrl = app.serverUrl;
    wx.showLoading({
      title: '請等待,加載中...',
    })

    wx.request({
      url:serverUrl+'/video/showAll?page='+page,
      method:"POST",
      success:function(res){
        wx.hideLoading();

        console.log(res.data);

      }
    })
  }

 

  

const app = getApp()

Page({
  data: {
    // 用於分頁的屬性
    totalPage:1,
    page:1,
    videoList:[],
    screenWidth: 350,
    //用於展現圖片
    serverUrl:""
  },

  onLoad: function (params) {
    var me = this;
    var screenWidth = wx.getSystemInfoSync().screenWidth;

    me.setData({
      screenWidth: screenWidth,
    });

    //獲取當前的分頁數
    var page = me.data.page;
    var serverUrl = app.serverUrl;
    wx.showLoading({
      title: '請等待,加載中...',
    })

    wx.request({
      url:serverUrl+'/video/showAll?page='+page,
      method:"POST",
      success:function(res){
        wx.hideLoading();

        console.log(res.data);

      }
    })
  }
})
index.js

 

  前端微信小程序展現與後端接口的聯調

 

  <view wx:for="{{videoList}}" wx:key="" class="item-container">  



     <view style='width:{{screenWidth}}px;height:210px;' class='back-img'> 
        <image src="{{serverUrl}}{{item.coverPath}}" style='width:{{screenWidth}}px;height:210px;' mode="aspectFit" bindtap='showVideoInfo' data-arrindex='{{index}}'></image>
     </view> 


    <view class="desc">
        <view class="faceName">
            <image class='myface' src="{{serverUrl}}{{item.face_image}}"></image>
            <view class="nickname">{{item.nickname}}</view>
        </view>
    </view>


  </view>  
  
index.wxml

 

const app = getApp()

Page({
  data: {
    // 用於分頁的屬性
    totalPage:1,
    page:1,
    videoList:[],
    screenWidth: 350,
    //用於展現圖片
    serverUrl:""
  },

  onLoad: function (params) {
    var me = this;
    var screenWidth = wx.getSystemInfoSync().screenWidth;

    me.setData({
      screenWidth: screenWidth,
    });

    //獲取當前的分頁數
    var page = me.data.page;
    var serverUrl = app.serverUrl;
    wx.showLoading({
      title: '請等待,加載中...',
    })

    wx.request({
      url:serverUrl+'/video/showAll?page='+page,
      method:"POST",
      success:function(res){
        wx.hideLoading();

        console.log(res.data);
        //判斷當前頁面page是不是第一頁,若是是第一頁,那麼設置videoList爲空
        if(page==1){
          me.setData({
            videoList: []
          });
        }

        var videoList = res.data.data.rows;
        var newVideoList = me.data.videoList;

        me.setData({
          videoList: newVideoList.concat(videoList),
          page:page,
          totalPage: res.data.data.total,
          serverUrl: serverUrl
        });

      }
    })
  }
})
index.js

 

 

首頁視頻列表-上拉分頁

  小程序使用上拉刷新方法onReachBottom()

  封裝顯示視頻方法getAllVideoList()

 getAllVideoList:function(page){
    var serverUrl = app.serverUrl;
    wx.showLoading({
      title: '請等待,加載中...',
    })

    wx.request({
      url: serverUrl + '/video/showAll?page=' + page,
      method: "POST",
      success: function (res) {
        wx.hideLoading();

        console.log(res.data);
        //判斷當前頁面page是不是第一頁,若是是第一頁,那麼設置videoList爲空
        if (page == 1) {
          me.setData({
            videoList: []
          });
        }

        var videoList = res.data.data.rows;
        var newVideoList = me.data.videoList;

        me.setData({
          videoList: newVideoList.concat(videoList),
          page: page,
          totalPage: res.data.data.total,
          serverUrl: serverUrl
        });

      }
    })
  }

 

   實現上拉刷新,當刷新頁數大於後臺設置的5時候,會暫時數據庫中後5個視頻,直到將數據庫中全部的視頻都展現徹底

 

  <view wx:for="{{videoList}}" wx:key="" class="item-container">  



     <view style='width:{{screenWidth}}px;height:210px;' class='back-img'> 
        <image src="{{serverUrl}}{{item.coverPath}}" style='width:{{screenWidth}}px;height:210px;' mode="aspectFit" bindtap='showVideoInfo' data-arrindex='{{index}}'></image>
     </view> 


    <view class="desc">
        <view class="faceName">
            <image class='myface' src="{{serverUrl}}{{item.face_image}}"></image>
            <view class="nickname">{{item.nickname}}</view>
        </view>
    </view>


  </view>  
  
index.wxml

 

const app = getApp()

Page({
  data: {
    // 用於分頁的屬性
    totalPage:1,
    page:1,
    videoList:[],
    screenWidth: 350,
    //用於展現圖片
    serverUrl:""
  },

  onLoad: function (params) {
    var me = this;
    var screenWidth = wx.getSystemInfoSync().screenWidth;

    me.setData({
      screenWidth: screenWidth,
    });

    //獲取當前的分頁數
    var page = me.data.page;
    me.getAllVideoList(page);
  },

  getAllVideoList:function(page){
    var me = this;
    var serverUrl = app.serverUrl;
    wx.showLoading({
      title: '請等待,加載中...',
    })

    wx.request({
      url: serverUrl + '/video/showAll?page=' + page,
      method: "POST",
      success: function (res) {
        wx.hideLoading();

        console.log(res.data);
        //判斷當前頁面page是不是第一頁,若是是第一頁,那麼設置videoList爲空
        if (page == 1) {
          me.setData({
            videoList: []
          });
        }

        var videoList = res.data.data.rows;
        var newVideoList = me.data.videoList;

        me.setData({
          videoList: newVideoList.concat(videoList),
          page: page,
          totalPage: res.data.data.total,
          serverUrl: serverUrl
        });

      }
    })
  },

  onReachBottom:function(){
    var me = this;
    var currentPage = me.data.page;
    var totalPage = me.data.totalPage;

    //判斷當前頁數和總頁數是否相等,若是相等則不須要查詢
    if (currentPage == totalPage){
      wx.showToast({
        title: '已經沒有視頻啦~~',
        icon:"none"
      })
      return ;
    }

    var page = currentPage + 1;

    me.getAllVideoList(page);
  }

})
index.js

 

 

首頁視頻列表-下拉刷新

  微信小程序onPullDownRefresh頁面相關事件處理函數--監聽用戶下拉動做,enablePullDownRefresh開啓下拉刷新

  在index.json中開啓下拉刷新熟悉

{
  "enablePullDownRefresh":true,
  "backgroundTextStyle":"dark"
}

 

  wx.showNavigationBarLoading()在當前頁面顯示導航條加載動畫

 

{
  "enablePullDownRefresh":true,
  "backgroundTextStyle":"dark"
}
index.json

 

  <view wx:for="{{videoList}}" wx:key="" class="item-container">  



     <view style='width:{{screenWidth}}px;height:210px;' class='back-img'> 
        <image src="{{serverUrl}}{{item.coverPath}}" style='width:{{screenWidth}}px;height:210px;' mode="aspectFit" bindtap='showVideoInfo' data-arrindex='{{index}}'></image>
     </view> 


    <view class="desc">
        <view class="faceName">
            <image class='myface' src="{{serverUrl}}{{item.face_image}}"></image>
            <view class="nickname">{{item.nickname}}</view>
        </view>
    </view>


  </view>  
  
index.wxml

 

const app = getApp()

Page({
  data: {
    // 用於分頁的屬性
    totalPage:1,
    page:1,
    videoList:[],
    screenWidth: 350,
    //用於展現圖片
    serverUrl:""
  },

  onLoad: function (params) {
    var me = this;
    var screenWidth = wx.getSystemInfoSync().screenWidth;

    me.setData({
      screenWidth: screenWidth,
    });

    //獲取當前的分頁數
    var page = me.data.page;
    me.getAllVideoList(page);
  },

  getAllVideoList:function(page){
    var me = this;
    var serverUrl = app.serverUrl;
    wx.showLoading({
      title: '請等待,加載中...',
    })

    wx.request({
      url: serverUrl + '/video/showAll?page=' + page,
      method: "POST",
      success: function (res) {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        //中止當前頁面下拉刷新
        wx.stopPullDownRefresh();

        console.log(res.data);
        //判斷當前頁面page是不是第一頁,若是是第一頁,那麼設置videoList爲空
        if (page == 1) {
          me.setData({
            videoList: []
          });
        }

        var videoList = res.data.data.rows;
        var newVideoList = me.data.videoList;

        me.setData({
          videoList: newVideoList.concat(videoList),
          page: page,
          totalPage: res.data.data.total,
          serverUrl: serverUrl
        });

      }
    })
  },

  onPullDownRefresh:function(){
    wx.showNavigationBarLoading()
    this.getAllVideoList(1);
  },

  onReachBottom:function(){
    var me = this;
    var currentPage = me.data.page;
    var totalPage = me.data.totalPage;

    //判斷當前頁數和總頁數是否相等,若是相等則不須要查詢
    if (currentPage == totalPage){
      wx.showToast({
        title: '已經沒有視頻啦~~',
        icon:"none"
      })
      return ;
    }

    var page = currentPage + 1;

    me.getAllVideoList(page);
  }

})
index.js

 

 

視頻組件與api

  muted:設置video組件是否有聲音

  initial-time:指定視頻初始播放位置

  direction:設置全屏時視頻的方向,不指定則根據寬高比自動判斷

  controls:是否顯示默認播放控件(播放/暫停按鈕、播放進度、時間)

  duration:指定視頻時長

  danmu-list:彈幕列表

  enable-danmu:是否展現彈幕,只在初始化時有效,不能動態變動

  danmu-btn:是否顯示彈幕按鈕,只在初始化時有效,不能動態變動

  autoplay:是否自動播放

  loop:是否循環播放

  page-gesture:在非全屏模式下,是否開啓亮度與音量調節手勢(廢棄,見 vslide-gesture)

  direction:設置全屏時視頻的方向,不指定則根據寬高比自動判斷

 

<video src="http://192.168.1.110:8081/190502H6YA6C4ZR4/video/feff1fba-0f73-43ea-ae3a-52dbd5343926.mp4"
muted="{{true}}"
initial-time="2"
direction="3"
controls="{{true}}"
danmu-list="{{danmuList}}"
enable-danmu="{{true}}"
danmu-btn="{{true}}"
autoplay="{{false}}"
loop="{{true}}"
page-gesture="{{true}}"
direction="0"
></video>
videotest.wxml

 

const app = getApp()

Page({

  data: {
    danmuList: [
      {
        text: '第 1s 出現的彈幕',
        color: '#ff0000',
        time: 1
      },
      {
        text: '第 3s 出現的彈幕',
        color: '#ff00ff',
        time: 3
      }]
  }

})
videotest.js

 

 

視頻展現頁開發-視頻展現頁面

  開始視頻的展現頁面,將小視頻的視頻填充滿整個頁面 

 

<view style='width:100%;height:100%;'>

<video   src="http://192.168.1.110:8081/190502H6YA6C4ZR4/video/feff1fba-0f73-43ea-ae3a-52dbd5343926.mp4"
muted="{{true}}"
controls="{{false}}"

autoplay="{{true}}"
loop="{{true}}"

enable-progress-gesture="{{false}}"
style='width:100%;height:100%;'
objectFit='{{cover}}'
></video>

</view>
videoinfo.wxml

 

const app = getApp()

Page({
  data: {
    cover:"cover"
  }

})
videoinfo.js

 

 

視頻展現頁開發-圖標放置

  cover-view組件:覆蓋在文本之上的組件

  爲方便展現效果,我換了一個視頻做爲展現

  上方上傳視頻、搜索按鈕圖標button的放置

<cover-view class='container'>
            <!-- 上傳視頻 -->

            <cover-image src='../resource/images/camera.png' style='width:50rpx;height:50rpx;' bindtap='upload'></cover-image>


            <!-- 搜索按鈕 -->
            <cover-image src='../resource/images/search.png' style='width:45rpx;height:45rpx;' bindtap='showSearch'></cover-image>

</cover-view>

 

  左側圖標用戶頭像、喜歡收藏按鈕、評論按鈕、分享按鈕的放置

<cover-view class='container-me'>
            <!-- 頭像 -->
            <cover-image class="face" src='{{publisher.faceImage}}' bindtap='showPublisher'></cover-image>


            <!-- 喜歡收藏按鈕 -->
            <block wx:if="{{userLikeVideo}}">
                <cover-image class="size-me" src='../resource/images/like.png' style='margin-top:30rpx;' bindtap='likeVideoOrNot'></cover-image>
            </block>
            <block wx:else>
                <cover-image class="size-me" src='../resource/images/unlike.png' style='margin-top:30rpx;' bindtap='likeVideoOrNot'></cover-image>
            </block>


            <!-- 評論按鈕 -->
            <cover-image class="size-me" src='../resource/images/comments.png' style='margin-top:30rpx;' bindtap='leaveComment'></cover-image>

            <!-- 分享按鈕 -->
            <cover-image class="size-me" src='../resource/images/share.png' style='margin-top:30rpx;' bindtap='shareMe'></cover-image>

</cover-view>

 

  下方首頁按鈕和個人按鈕圖標放置

<cover-view class='container-bottom'>
            <!-- 首頁按鈕 -->
            <cover-image class='' src='../resource/images/index.png' class="size-bottom" bindtap='showIndex'></cover-image>

            <!-- 個人關注 -->
            <cover-image class='' src='../resource/images/follow.png' class="size-bottom" bindtap='showFollow'></cover-image>

            <!-- 個人按鈕 -->
            <cover-image class='' src='../resource/images/mine.png' class="size-bottom" bindtap='showMine'></cover-image>

</cover-view>

 

 

<view style='width:100%;height:100%;'>

<video   src="http://1257737090.vod2.myqcloud.com/d7d12d2bvodcq1257737090/f42e13285285890785678595639/rG447485Zc0A.mp4"
muted="{{true}}"

autoplay="{{true}}"
loop="{{true}}"

enable-progress-gesture="{{false}}"
style='width:100%;height:100%;'
objectFit='{{cover}}'
>

<cover-view class='container'>
            <!-- 上傳視頻 -->

            <cover-image src='../resource/images/camera.png' style='width:50rpx;height:50rpx;' bindtap='upload'></cover-image>


            <!-- 搜索按鈕 -->
            <cover-image src='../resource/images/search.png' style='width:45rpx;height:45rpx;' bindtap='showSearch'></cover-image>

</cover-view>

<cover-view class='container-me'>
            <!-- 頭像 -->
            <cover-image class="face" src='{{publisher.faceImage}}' bindtap='showPublisher'></cover-image>


            <!-- 喜歡收藏按鈕 -->
            <block wx:if="{{userLikeVideo}}">
                <cover-image class="size-me" src='../resource/images/like.png' style='margin-top:30rpx;' bindtap='likeVideoOrNot'></cover-image>
            </block>
            <block wx:else>
                <cover-image class="size-me" src='../resource/images/unlike.png' style='margin-top:30rpx;' bindtap='likeVideoOrNot'></cover-image>
            </block>


            <!-- 評論按鈕 -->
            <cover-image class="size-me" src='../resource/images/comments.png' style='margin-top:30rpx;' bindtap='leaveComment'></cover-image>

            <!-- 分享按鈕 -->
            <cover-image class="size-me" src='../resource/images/share.png' style='margin-top:30rpx;' bindtap='shareMe'></cover-image>

</cover-view>

 <cover-view class='container-words'>

            <cover-view>@{{publisher.nickname}}</cover-view>

            <cover-view class='video-desc'>{{videoInfo.videoDesc}}</cover-view>



</cover-view>


<cover-view class='container-bottom'>
            <!-- 首頁按鈕 -->
            <cover-image class='' src='../resource/images/index.png' class="size-bottom" bindtap='showIndex'></cover-image>

            <!-- 個人關注 -->
            <cover-image class='' src='../resource/images/follow.png' class="size-bottom" bindtap='showFollow'></cover-image>

            <!-- 個人按鈕 -->
            <cover-image class='' src='../resource/images/mine.png' class="size-bottom" bindtap='showMine'></cover-image>

</cover-view>


</video>

</view>
videoinfo.wxml

 

page {
    height: 100%;
    background-color: #141414;
}

.container {
    display: flex;
    margin-top: 20rpx;
    margin-left: 50rpx;
    margin-right: 50rpx;
    justify-content: space-between;
}

.container-me {
    margin-top: 360rpx;
    margin-left: 50rpx;
    width: 80rpx;
}

.container-words {
    /* display: flex;
    flex-direction: column; */
    margin-top: 60rpx;
    margin-left: 50rpx;
    width: 100%;
    color: white;
    font-size: 14px;
}

.inputText {
    background-color: gainsboro;
    height: 35px;
}

.video-desc {
    width: 600rpx;
    height: 100rpx;
    white-space: pre-wrap;
}

.container-bottom {
    /* bottom: 10px;  */
    display: flex;
    margin-top: 60rpx;
    margin-left: 50rpx;
    margin-right: 50rpx;
    /* margin-bottom: 10rpx; */
    justify-content: space-between;
    /* position: fixed;  */
}

.size-me {
    width: 70rpx;
    height: 70rpx;
}

.size-me-bgm {
    width: 40rpx;
    height: 40rpx;
}

.bgm-style {
    display: flex;
    flex-direction: row;
}

.size-bottom {
    width: 60rpx;
    height: 60rpx;
}

.face2 {
    width: 75rpx;
    height: 75rpx;
    border: 0 solid #f00;
    border-radius: 100rpx;
    background-color: #f10b2e;
}

.face {
    width: 75rpx;
    height: 75rpx;
    /* margin: 20rpx; */
    border-radius: 50%;
}

.icoBtn {
    flex: 1;
    width: 80rpx;
    height: 100%;
}


.comments-scoll {
    height: 1200rpx;
}


.comments-all {
    /* margin-top: 10px; */
      margin-bottom: 10px;  
      /* border-bottom: solid 1px gray;   */
    background-color: #141414;
    color: #e8e8e8;
}

.face-comments {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    margin-left: 5px;
}

.container-comments{
    display: flex;
    
    /* margin-top: 20rpx;
    margin-left: 50rpx;
    margin-right: 50rpx;
    justify-content: space-between; */
    
}


.nickname-comments {
    margin-left: 10px;
}

.nickname-lbl{
    color: #a1a1a1;
}

.date-lbl{
    color: #a1a1a1;
}

.comments-content{
    margin-left: 5px;
    margin-right: 5px;
    /* margin-bottom: 10px; */
    border-bottom: solid 1px #232323;
    background-color: #141414;
}

.saySthView {
    padding: 10px;
    background-color: #141414;
    line-height: 45px;
    border-bottom: solid 1px #232323;
    color: white;
}

.saySth {
    margin-top: 10px;
    margin-left: 10px;
    font-size: 18px;
}
videoinfo.wxss

 

const app = getApp()

Page({
  data: {
    cover:"cover"
  }

})
videoinfo.js

 

 

開源搜索視頻組件的使用

  使用開源視頻組件 github傳送門

 

searchVideo.wxml

<include src="../../wxSearchView/wxSearchView.wxml" />

 

searchVideo.wxss

@import "../../wxSearchView/wxSearchView.wxss";

 

// 1 導入js文件
var WxSearch = require('../../wxSearchView/wxSearchView.js');


Page({

  data: {

  },

  onLoad: function () {

    // 2 搜索欄初始化
    var that = this;
    WxSearch.init(
      that,  // 本頁面一個引用
      ['校園視', 'Gary', "搞笑", "幽默", '校園', '嚴肅'], // 熱點搜索推薦,[]表示不使用
      [],// 搜索匹配,[]表示不使用
      that.mySearchFunction, // 提供一個搜索回調函數
      that.myGobackFunction //提供一個返回回調函數
    );

  },

  // 3 轉發函數,固定部分,直接拷貝便可
  wxSearchInput: WxSearch.wxSearchInput,  // 輸入變化時的操做
  wxSearchKeyTap: WxSearch.wxSearchKeyTap,  // 點擊提示或者關鍵字、歷史記錄時的操做
  wxSearchDeleteAll: WxSearch.wxSearchDeleteAll, // 刪除全部的歷史記錄
  wxSearchConfirm: WxSearch.wxSearchConfirm,  // 搜索函數
  wxSearchClear: WxSearch.wxSearchClear,  // 清空函數

  // 4 搜索回調函數  
  mySearchFunction: function (value) {
    // do your job here
    // 示例:跳轉
    wx.redirectTo({
      url: '../index/index?searchValue=' + value
    })
  },

  // 5 返回回調函數
  myGobackFunction: function () {
    // do your job here
    // 示例:返回
    wx.redirectTo({
      url: '../index/index?searchValue=返回'
    })
  }

})
searchVideo.js

 

 

修改全局用戶對象使用緩存

  在app.js中添加兩個方法

//設置全局用戶對象
  setGlobalUserInfo:function(user){
    wx.setStorageSync("userInfo", user)
  },

//獲取全局用戶對象
  getGlobalUserInfo: function () {
    return wx.getStorageSync("userInfo")
  }

 

  修改app.userInfo中的值

  

 

 

 查詢接口完善以及熱搜詞搜索

  開發查詢接口和熱搜詞接口

//分頁和搜索查詢視頻列表
    //isSaveRecord:1  須要保存  0  不須要保存或爲空
    @PostMapping(value="/showAll")
    public IMoocJSONResult showAll(@RequestBody Videos video,Integer isSaveRecord ,
            Integer page) throws Exception {
        
        if(page == null) {
            page = 1;
        }
        
        PagedResult result = videoService.getAllVideos(video,isSaveRecord,page,PAGE_SIZE);
        return IMoocJSONResult.ok(result);
        
    }
    
    
    @PostMapping(value="/hot")
    public IMoocJSONResult hot() throws Exception {
        
        return IMoocJSONResult.ok(videoService.getHotwords());
    }

 

  VideoServiceImpl視頻熱搜詞方法getHotwords()

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<String> getHotwords() {
        
        return searchRecordsMapper.getHotwords();
    }

 

  往數據庫中添加一些假數據Gary數據有4條,perfect數據有2條,school數據有1條,熱搜詞搜索後,數據將從Gary->perfect->school順序進行排序

  

  在searchVideo.js中進行小程序先後端連調

onLoad: function () {

    // 2 搜索欄初始化
    var that = this;

    //查詢熱搜詞
    var serverUrl = app.serverUrl;
    wx.request({
      url: serverUrl+'/video/hot',
      method:"POST",
      success:function(res){
          console.log(res);
          var hotList = res.data.data;
          WxSearch.init(
          that,  // 本頁面一個引用
          hotList,
         // ['校園視', 'Gary', "搞笑", "幽默", '校園', '嚴肅'], // 熱點搜索推薦,[]表示不使用
          hotList,// 搜索匹配,[]表示不使用
          that.mySearchFunction, // 提供一個搜索回調函數
          that.myGobackFunction //提供一個返回回調函數
        );
      }
    })

  },

 

 

 

// 1 導入js文件
var WxSearch = require('../../wxSearchView/wxSearchView.js');

const app = getApp()

Page({

  data: {

  },

  onLoad: function () {

    // 2 搜索欄初始化
    var that = this;

    //查詢熱搜詞
    var serverUrl = app.serverUrl;
    wx.request({
      url: serverUrl+'/video/hot',
      method:"POST",
      success:function(res){
          console.log(res);
          var hotList = res.data.data;
          WxSearch.init(
          that,  // 本頁面一個引用
          hotList,
         // ['校園視', 'Gary', "搞笑", "幽默", '校園', '嚴肅'], // 熱點搜索推薦,[]表示不使用
          hotList,// 搜索匹配,[]表示不使用
          that.mySearchFunction, // 提供一個搜索回調函數
          that.myGobackFunction //提供一個返回回調函數
        );
      }
    })

  },

  // 3 轉發函數,固定部分,直接拷貝便可
  wxSearchInput: WxSearch.wxSearchInput,  // 輸入變化時的操做
  wxSearchKeyTap: WxSearch.wxSearchKeyTap,  // 點擊提示或者關鍵字、歷史記錄時的操做
  wxSearchDeleteAll: WxSearch.wxSearchDeleteAll, // 刪除全部的歷史記錄
  wxSearchConfirm: WxSearch.wxSearchConfirm,  // 搜索函數
  wxSearchClear: WxSearch.wxSearchClear,  // 清空函數

  // 4 搜索回調函數  
  mySearchFunction: function (value) {
    // do your job here
    // 示例:跳轉
    wx.redirectTo({
      url: '../index/index?searchValue=' + value
    })
  },

  // 5 返回回調函數
  myGobackFunction: function () {
    // do your job here
    // 示例:返回
    wx.redirectTo({
      url: '../index/index?searchValue=返回'
    })
  }

})
searchVideo.js

 

 

搜索功能整合首頁列表聯調

   完善searchVideo.js中搜索回調函數和返回回調函數

 // 4 搜索回調函數  
  mySearchFunction: function (value) {
    // do your job here
    // 示例:跳轉
    wx.redirectTo({
      url: '../index/index?isSaveRecord=1&search=' + value
    })
  },

  // 5 返回回調函數
  myGobackFunction: function () {
    // do your job here
    // 示例:返回
    wx.redirectTo({
      url: '../index/index'
    })
  }

 

  查看數據庫中videos數據庫表

 

   VideosMapperCustom.xml中數據的模糊查詢

  <select id="queryAllVideos" resultMap="BaseResultMap" parameterType="String">
  
      select v.*,u.face_image as face_image,u.nickname as nickname from videos v
      left join users u on u.id = v.user_id
      where
          1 =1
          <if test="videoDesc != null and videoDesc != '' ">
              and v.video_desc like '%${videoDesc}%'
          </if>
          and v.status = 1
      order by v.create_time desc
  
  </select>

 

 

const app = getApp()

Page({
  data: {
    // 用於分頁的屬性
    totalPage:1,
    page:1,
    videoList:[],
    screenWidth: 350,
    //用於展現圖片
    serverUrl:"",
    searchContent:""
  },

  onLoad: function (params) {
    var me = this;
    var screenWidth = wx.getSystemInfoSync().screenWidth;

    me.setData({
      screenWidth: screenWidth,
    });

    var searchContent = params.search;
    var isSaveRecord = params.isSaveRecord;
    if (isSaveRecord == null || isSaveRecord == '' || isSaveRecord==undefined){
      isSaveRecord = 0;
    }

    me.setData({
      searchContent: searchContent
    });

    //獲取當前的分頁數
    var page = me.data.page;
    me.getAllVideoList(page, isSaveRecord);
  },

  getAllVideoList: function (page, isSaveRecord){
    var me = this;
    var serverUrl = app.serverUrl;
    wx.showLoading({
      title: '請等待,加載中...',
    })

    var searchContent = me.data.searchContent;

    wx.request({
      url: serverUrl + '/video/showAll?page=' + page + "&isSaveRecord=" + isSaveRecord,
      method: "POST",
      data:{
        videoDesc: searchContent
      },
      success: function (res) {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        //中止當前頁面下拉刷新
        wx.stopPullDownRefresh();

        console.log(res.data);
        //判斷當前頁面page是不是第一頁,若是是第一頁,那麼設置videoList爲空
        if (page == 1) {
          me.setData({
            videoList: []
          });
        }

        var videoList = res.data.data.rows;
        var newVideoList = me.data.videoList;

        me.setData({
          videoList: newVideoList.concat(videoList),
          page: page,
          totalPage: res.data.data.total,
          serverUrl: serverUrl
        });

      }
    })
  },

  onPullDownRefresh:function(){
    wx.showNavigationBarLoading()
    this.getAllVideoList(1,0);
  },

  onReachBottom:function(){
    var me = this;
    var currentPage = me.data.page;
    var totalPage = me.data.totalPage;

    //判斷當前頁數和總頁數是否相等,若是相等則不須要查詢
    if (currentPage == totalPage){
      wx.showToast({
        title: '已經沒有視頻啦~~',
        icon:"none"
      })
      return ;
    }

    var page = currentPage + 1;

    me.getAllVideoList(page,0);
  }

})
index.js

 

// 1 導入js文件
var WxSearch = require('../../wxSearchView/wxSearchView.js');

const app = getApp()

Page({

  data: {

  },

  onLoad: function () {

    // 2 搜索欄初始化
    var that = this;

    //查詢熱搜詞
    var serverUrl = app.serverUrl;
    wx.request({
      url: serverUrl+'/video/hot',
      method:"POST",
      success:function(res){
          console.log(res);
          var hotList = res.data.data;
          WxSearch.init(
          that,  // 本頁面一個引用
          hotList,
         // ['校園視', 'Gary', "搞笑", "幽默", '校園', '嚴肅'], // 熱點搜索推薦,[]表示不使用
          hotList,// 搜索匹配,[]表示不使用
          that.mySearchFunction, // 提供一個搜索回調函數
          that.myGobackFunction //提供一個返回回調函數
        );
      }
    })

  },

  // 3 轉發函數,固定部分,直接拷貝便可
  wxSearchInput: WxSearch.wxSearchInput,  // 輸入變化時的操做
  wxSearchKeyTap: WxSearch.wxSearchKeyTap,  // 點擊提示或者關鍵字、歷史記錄時的操做
  wxSearchDeleteAll: WxSearch.wxSearchDeleteAll, // 刪除全部的歷史記錄
  wxSearchConfirm: WxSearch.wxSearchConfirm,  // 搜索函數
  wxSearchClear: WxSearch.wxSearchClear,  // 清空函數

  // 4 搜索回調函數  
  mySearchFunction: function (value) {
    // do your job here
    // 示例:跳轉
    wx.redirectTo({
      url: '../index/index?isSaveRecord=1&search=' + value
    })
  },

  // 5 返回回調函數
  myGobackFunction: function () {
    // do your job here
    // 示例:返回
    wx.redirectTo({
      url: '../index/index'
    })
  }

})
searchVideo.js

 

 

熱搜查詢聯調與視頻對象的播放與暫停

  微信小程序前端控制音頻播放muted="{{false}}"

  在videoinfo.wxml中給<video>組件添加一個id

<video   id="myVideo" src="http://1257737090.vod2.myqcloud.com/d7d12d2bvodcq1257737090/f42e13285285890785678595639/rG447485Zc0A.mp4"

 

  在videoinfo.js中使用生命週期函數onLoad(),onShow(),onHide()實現

  videoCtx:{

  },

  onLoad:function(){
    var me = this;
    me.videoCtx = wx.createVideoContext("myVideo", me);
  },

  onShow:function(){
    var me = this;
    me.videoCtx.play();
  },

  onHide:function(){
    var me = this;
    me.videoCtx.pause();
  },

 

const app = getApp()

Page({
  data: {
    cover:"cover"
  },

  videoCtx:{

  },

  onLoad:function(){
    var me = this;
    me.videoCtx = wx.createVideoContext("myVideo", me);
  },

  onShow:function(){
    var me = this;
    me.videoCtx.play();
  },

  onHide:function(){
    var me = this;
    me.videoCtx.pause();
  },


  showSearch:function(){
    wx.navigateTo({
      url: '../searchVideo/searchVideo',
    })
  }

})
videoinfo.js

 

 

實現點擊相機上傳我的

  實現上傳代碼複用

function uploadVideo() {
  var me = this;

  wx.chooseVideo({
    sourceType: ['album'],
    success: function (res) {
      console.log(res);

      var duration = res.duration;
      var tmpHeight = res.height;
      var tmpWidth = res.width;
      var tmpVideoUrl = res.tempFilePath;
      var tmpCoverUrl = res.thumbTempFilePath;

      if (duration > 11) {
        wx.showToast({
          title: '視頻長度不能超過10秒...',
          icon: "none",
          duration: 2500
        })
      } else if (duration < 1) {
        wx.showToast({
          title: '視頻長度過短,請上傳超過1秒的視頻...',
          icon: "none",
          duration: 2500
        })
      } else {
        // 打開選擇bgm的頁面
        wx.navigateTo({
          url: '../chooseBgm/chooseBgm?duration=' + duration
          + "&tmpHeight=" + tmpHeight
          + "&tmpWidth=" + tmpWidth
          + "&tmpVideoUrl=" + tmpVideoUrl
          + "&tmpCoverUrl=" + tmpCoverUrl
          ,
        })
      }

    }
  })

}

module.exports = {
  uploadVideo: uploadVideo
}
videoUtil.js

 

 

var videoUtil = require('../../utils/videoUtil.js')

const app = getApp()

Page({
  data: {
    cover:"cover"
  },

  videoCtx:{

  },

  onLoad:function(){
    var me = this;
    me.videoCtx = wx.createVideoContext("myVideo", me);
  },

  onShow:function(){
    var me = this;
    me.videoCtx.play();
  },

  onHide:function(){
    var me = this;
    me.videoCtx.pause();
  },


  showSearch:function(){
    wx.navigateTo({
      url: '../searchVideo/searchVideo',
    })
  },

  upload:function(){
    videoUtil.uploadVideo();
  }

})
videoinfo.js

 

 

首頁進入視頻展現頁

  在videoInfo.js添加showVideoInfo()方法,當用戶點擊圖片時候觸發showVideoInfo()方法

<image src="{{serverUrl}}{{item.coverPath}}" style='width:{{screenWidth}}px;height:210px;' mode="aspectFit" bindtap='showVideoInfo' data-arrindex='{{index}}'></image>

 

  showVideoInfo:function(e){
      var me = this;
      var videoList = me.data.videoList;
      var arrindex = e.target.dataset.arrindex;
    var videoInfo = JSON.stringify(videoList[arrindex]);

    wx.redirectTo({
      url: '../videoinfo/videoinfo?videoInfo='+videoInfo,
    })
  }

 

  在videoInfo.js中的onload()接收來自index.js中的值

  onLoad:function(params){
    var me = this;
    me.videoCtx = wx.createVideoContext("myVideo", me);

    //獲取上一個頁面傳入的參數
    var videoInfo = JSON.parse(params.videoInfo);
    me.setData({
      videoInfo: videoInfo.id,
      src:app.serverUrl + videoInfo.videoPath,
      videoInfo: videoInfo
    });
  },

 

 

const app = getApp()

Page({
  data: {
    // 用於分頁的屬性
    totalPage:1,
    page:1,
    videoList:[],
    screenWidth: 350,
    //用於展現圖片
    serverUrl:"",
    searchContent:""
  },

  onLoad: function (params) {
    var me = this;
    var screenWidth = wx.getSystemInfoSync().screenWidth;

    me.setData({
      screenWidth: screenWidth,
    });

    var searchContent = params.search;
    var isSaveRecord = params.isSaveRecord;
    if (isSaveRecord == null || isSaveRecord == '' || isSaveRecord==undefined){
      isSaveRecord = 0;
    }

    me.setData({
      searchContent: searchContent
    });

    //獲取當前的分頁數
    var page = me.data.page;
    me.getAllVideoList(page, isSaveRecord);
  },

  getAllVideoList: function (page, isSaveRecord){
    var me = this;
    var serverUrl = app.serverUrl;
    wx.showLoading({
      title: '請等待,加載中...',
    })

    var searchContent = me.data.searchContent;

    wx.request({
      url: serverUrl + '/video/showAll?page=' + page + "&isSaveRecord=" + isSaveRecord,
      method: "POST",
      data:{
        videoDesc: searchContent
      },
      success: function (res) {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        //中止當前頁面下拉刷新
        wx.stopPullDownRefresh();

        console.log(res.data);
        //判斷當前頁面page是不是第一頁,若是是第一頁,那麼設置videoList爲空
        if (page == 1) {
          me.setData({
            videoList: []
          });
        }

        var videoList = res.data.data.rows;
        var newVideoList = me.data.videoList;

        me.setData({
          videoList: newVideoList.concat(videoList),
          page: page,
          totalPage: res.data.data.total,
          serverUrl: serverUrl
        });

      }
    })
  },

  onPullDownRefresh:function(){
    wx.showNavigationBarLoading()
    this.getAllVideoList(1,0);
  },

  onReachBottom:function(){
    var me = this;
    var currentPage = me.data.page;
    var totalPage = me.data.totalPage;

    //判斷當前頁數和總頁數是否相等,若是相等則不須要查詢
    if (currentPage == totalPage){
      wx.showToast({
        title: '已經沒有視頻啦~~',
        icon:"none"
      })
      return ;
    }

    var page = currentPage + 1;

    me.getAllVideoList(page,0);
  },

  showVideoInfo:function(e){
      var me = this;
      var videoList = me.data.videoList;
      var arrindex = e.target.dataset.arrindex;
    var videoInfo = JSON.stringify(videoList[arrindex]);

    wx.redirectTo({
      url: '../videoinfo/videoinfo?videoInfo='+videoInfo,
    })
  }

})
index.js

 

var videoUtil = require('../../utils/videoUtil.js')

const app = getApp()

Page({
  data: {
    cover:"cover",
    videoId:"",
    src:"",
    videoInfo:{}
  },

  videoCtx:{

  },

  onLoad:function(params){
    var me = this;
    me.videoCtx = wx.createVideoContext("myVideo", me);

    //獲取上一個頁面傳入的參數
    var videoInfo = JSON.parse(params.videoInfo);
    me.setData({
      videoInfo: videoInfo.id,
      src:app.serverUrl + videoInfo.videoPath,
      videoInfo: videoInfo
    });
  },

  onShow:function(){
    var me = this;
    me.videoCtx.play();
  },

  onHide:function(){
    var me = this;
    me.videoCtx.pause();
  },


  showSearch:function(){
    wx.navigateTo({
      url: '../searchVideo/searchVideo',
    })
  },

  upload:function(){
    videoUtil.uploadVideo();
  }

})
videoinfo.js

 

 

  爲加強用戶體驗,實現用戶上傳視頻時候橫豎屏的轉換

onLoad:function(params){
    var me = this;
    me.videoCtx = wx.createVideoContext("myVideo", me);

    //獲取上一個頁面傳入的參數
    var videoInfo = JSON.parse(params.videoInfo);

    var height = videoInfo.videoHeight;
    var width = videoInfo.videoWidth;
    var cover = "cover";
    if(width>=height){
      cover="";
    }

    me.setData({
      videoInfo: videoInfo.id,
      src:app.serverUrl + videoInfo.videoPath,
      videoInfo: videoInfo,
      cover:cover
    });
  },

 

var videoUtil = require('../../utils/videoUtil.js')

const app = getApp()

Page({
  data: {
    cover:"cover",
    videoId:"",
    src:"",
    videoInfo:{}
  },

  videoCtx:{

  },

  onLoad:function(params){
    var me = this;
    me.videoCtx = wx.createVideoContext("myVideo", me);

    //獲取上一個頁面傳入的參數
    var videoInfo = JSON.parse(params.videoInfo);

    var height = videoInfo.videoHeight;
    var width = videoInfo.videoWidth;
    var cover = "cover";
    if(width>=height){
      cover="";
    }

    me.setData({
      videoInfo: videoInfo.id,
      src:app.serverUrl + videoInfo.videoPath,
      videoInfo: videoInfo,
      cover:cover
    });
  },

  onShow:function(){
    var me = this;
    me.videoCtx.play();
  },

  onHide:function(){
    var me = this;
    me.videoCtx.pause();
  },


  showSearch:function(){
    wx.navigateTo({
      url: '../searchVideo/searchVideo',
    })
  },

  upload:function(){
    videoUtil.uploadVideo();
  }

})
videoinfo.js
相關文章
相關標籤/搜索