「小程序JAVA實戰」小程序上傳短視頻(46)

我的信息:用戶上傳短視頻。源碼:https://github.com/limingios/wxProgram.git 中wx-springboot 和 No.15html

業務流程

  1. 用戶選擇視頻(10秒限制),也能夠經過攝像頭拍攝
  2. 打開選擇背景音樂。
  3. 能夠選擇音樂或者不選擇輸入視頻的描述。
  4. controller 上傳視頻
  5. 保存視頻的截圖
  6. 用戶是否選擇背景音樂
    7.1 是:直接保存視頻
    7.2 否:合併視頻和背景音樂,保存視頻

微信插件

官方介紹:https://developers.weixin.qq.com/miniprogram/dev/api/media-video.html#wxchoosevideoobjectjava

  • 代碼修改
    > 能夠獲取到經過微信的組件獲取到視頻的長度,寬度,高度,視頻的截圖,視頻的臨時路徑,時長。而後針對這些能夠判斷出來是否容許上傳。
// pages/mine/mine.js
const app = getApp()
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    faceImage: "../../resource/images/noneface.png",
    nickname: "暱稱",
    fansCounts: 0,
    followCounts: 0,
    receiveLikeCounts: 0,
  },
  /**
   * 用戶註銷
   */
  logout:function(e){
    var user = app.userInfo;
    wx.showLoading({
      title: '正在註銷中。。。'
    });
    wx.request({
      url: app.serverUrl + "/logout?userId="+user.id,
      method: "POST",
      header: {
        'content-type': 'application/json' // 默認值
      },
      success: function (res) {
        console.log(res.data);
        var status = res.data.status;
        wx.hideLoading();
        if (status == 200) {
          wx.showToast({
            title: "用戶註銷成功~!",
            icon: 'none',
            duration: 3000
          })
          app.userInfo = null;
          wx.redirectTo({
            url: '../userRegister/userRegister',
          })

        } else if (status == 500) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 3000
          })
        }
      }
    })
  },
  /**
   * 頭像上傳
   */
  uploadFace:function(e){
    var user = app.userInfo;
    var me = this;
    wx.chooseImage({
      count: 1, // 默認9
      sizeType: ['compressed'], // 能夠指定是原圖仍是壓縮圖,默認兩者都有
      sourceType: ['album', 'camera'], // 能夠指定來源是相冊仍是相機,默認兩者都有
      success: function (res) {
        // 返回選定照片的本地文件路徑列表,tempFilePath能夠做爲img標籤的src屬性顯示圖片
        var tempFilePaths = res.tempFilePaths
        if (tempFilePaths.length>0){
          console.log(tempFilePaths[0]);
              wx.uploadFile({
                url: app.serverUrl + "/user/uploadFace?userId=" + user.id, //僅爲示例,非真實的接口地址
                filePath: tempFilePaths[0],
                name: 'file',
                success: function (res) {
                  var data = JSON.parse(res.data);
                  console.log(data);
                   wx.hideLoading();
                  if (data.status == 200) {
                    wx.showToast({
                      title: "用戶上傳成功~!",
                      icon: 'none',
                      duration: 3000
                    })
                    me.setData({
                      faceUrl: app.serverUrl+data.data
                    })


                  } else if (data.status == 500) {
                    wx.showToast({
                      title: data.msg,
                      icon: 'none',
                      duration: 3000
                    })
                  }
                }
              })
        }

      }
    })
  },
  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function (options) {
    var me = this;
    wx.showLoading({
      title: '正在獲取用戶信息。。。'
    });
    wx.request({
      url: app.serverUrl + "/user/queryByUserId?userId=" + app.userInfo.id,
      method: "POST",
      header: {
        'content-type': 'application/json' // 默認值
      },
      success: function (res) {
        console.log(res.data);
        var status = res.data.status;
        var userInfo = res.data.data;
        wx.hideLoading();
        var faceImage = me.data.faceUrl;
        if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage!=undefined){
          faceImage = app.serverUrl +userInfo.faceImage;
        }
        me.setData({
          faceImage: faceImage,
          fansCounts: userInfo.fansCounts,
          followCounts: userInfo.followCounts,
          receiveLikeCounts: userInfo.receiveLikeCounts,
          nickname: userInfo.nickname
        })
      }
    })
  },

  uploadVideo:function(e){
    var me = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        var tempDuration = res.duration;
        var tempHeight = res.height;
        var tempWidth = res.width;
        var tempSize = res.size;
        var tempFilePath = res.tempFilePath;
        var tempFilePath = res.thumbTempFilePath;
        if (tempDuration>20){
          wx.showToast({
            title: "視頻太長了老鐵不穩~",
            icon: 'none',
            duration: 3000
          })
        } else if (tempDuration <5){
          wx.showToast({
            title: "視頻過短了不到5秒。老鐵不穩~",
            icon: 'none',
            duration: 3000
          })
        } else{
          //進行上傳
        }
      }
    })
  },

  /**
   * 生命週期函數--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命週期函數--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命週期函數--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命週期函數--監聽頁面卸載
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函數--監聽用戶下拉動做
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函數
   */
  onReachBottom: function () {

  },

  /**
   * 用戶點擊右上角分享
   */
  onShareAppMessage: function () {

  }
})
複製代碼
  • 增長選擇背景音樂的界面

用戶能夠選擇視頻,接下來咱們選擇北京音樂的界面。用戶選擇音樂,或者用戶能夠不選擇音樂直接提交不選擇音樂直接提交。官方界面:https://developers.weixin.qq.com/miniprogram/dev/component/audio.htmlios

  • 新建頁面
// pages/mine/mine.js
const app = getApp()
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    faceImage: "../../resource/images/noneface.png",
    nickname: "暱稱",
    fansCounts: 0,
    followCounts: 0,
    receiveLikeCounts: 0,
  },
  /**
   * 用戶註銷
   */
  logout:function(e){
    var user = app.userInfo;
    wx.showLoading({
      title: '正在註銷中。。。'
    });
    wx.request({
      url: app.serverUrl + "/logout?userId="+user.id,
      method: "POST",
      header: {
        'content-type': 'application/json' // 默認值
      },
      success: function (res) {
        console.log(res.data);
        var status = res.data.status;
        wx.hideLoading();
        if (status == 200) {
          wx.showToast({
            title: "用戶註銷成功~!",
            icon: 'none',
            duration: 3000
          })
          app.userInfo = null;
          wx.redirectTo({
            url: '../userRegister/userRegister',
          })

        } else if (status == 500) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 3000
          })
        }
      }
    })
  },
  /**
   * 頭像上傳
   */
  uploadFace:function(e){
    var user = app.userInfo;
    var me = this;
    wx.chooseImage({
      count: 1, // 默認9
      sizeType: ['compressed'], // 能夠指定是原圖仍是壓縮圖,默認兩者都有
      sourceType: ['album', 'camera'], // 能夠指定來源是相冊仍是相機,默認兩者都有
      success: function (res) {
        // 返回選定照片的本地文件路徑列表,tempFilePath能夠做爲img標籤的src屬性顯示圖片
        var tempFilePaths = res.tempFilePaths
        if (tempFilePaths.length>0){
          console.log(tempFilePaths[0]);
              wx.uploadFile({
                url: app.serverUrl + "/user/uploadFace?userId=" + user.id, //僅爲示例,非真實的接口地址
                filePath: tempFilePaths[0],
                name: 'file',
                success: function (res) {
                  var data = JSON.parse(res.data);
                  console.log(data);
                   wx.hideLoading();
                  if (data.status == 200) {
                    wx.showToast({
                      title: "用戶上傳成功~!",
                      icon: 'none',
                      duration: 3000
                    })
                    me.setData({
                      faceUrl: app.serverUrl+data.data
                    })


                  } else if (data.status == 500) {
                    wx.showToast({
                      title: data.msg,
                      icon: 'none',
                      duration: 3000
                    })
                  }
                }
              })
        }

      }
    })
  },
  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function (options) {
    var me = this;
    wx.showLoading({
      title: '正在獲取用戶信息。。。'
    });
    wx.request({
      url: app.serverUrl + "/user/queryByUserId?userId=" + app.userInfo.id,
      method: "POST",
      header: {
        'content-type': 'application/json' // 默認值
      },
      success: function (res) {
        console.log(res.data);
        var status = res.data.status;
        var userInfo = res.data.data;
        wx.hideLoading();
        var faceImage = me.data.faceUrl;
        if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage!=undefined){
          faceImage = app.serverUrl +userInfo.faceImage;
        }
        me.setData({
          faceImage: faceImage,
          fansCounts: userInfo.fansCounts,
          followCounts: userInfo.followCounts,
          receiveLikeCounts: userInfo.receiveLikeCounts,
          nickname: userInfo.nickname
        })
      }
    })
  },

  uploadVideo:function(e){
    var me = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        var tempDuration = res.duration;
        var tempHeight = res.height;
        var tempWidth = res.width;
        var tempSize = res.size;
        var tempFilePath = res.tempFilePath;
        var thumbTempFilePath = res.thumbTempFilePath;
        if (tempDuration>20){
          wx.showToast({
            title: "視頻太長了老鐵不穩~",
            icon: 'none',
            duration: 3000
          })
        } else if (tempDuration <5){
          wx.showToast({
            title: "視頻過短了不到5秒。老鐵不穩~",
            icon: 'none',
            duration: 3000
          })
        } else{
          wx.navigateTo({
            url: '../chooseBgm/chooseBgm?tempDuration=' + tempDuration
              + '&tempHeight=' + tempHeight
              + '&tempWidth=' + tempWidth
              + '&tempSize=' + tempSize
              + '&tempFilePath=' + tempFilePath
              + '&thumbTempFilePath=' + thumbTempFilePath
          })
        }
      }
    })
  },

  /**
   * 生命週期函數--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命週期函數--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命週期函數--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命週期函數--監聽頁面卸載
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函數--監聽用戶下拉動做
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函數
   */
  onReachBottom: function () {

  },

  /**
   * 用戶點擊右上角分享
   */
  onShareAppMessage: function () {

  }
})
複製代碼
  • chooseBgm.wxml
<view>
    <form bindsubmit='upload'>

        <radio-group name="bgmId">
          <block wx:for="{{bgmList}}">
            <view class='container'>
              <audio name="{{item.name}}" author="{{item.author}}" src="{{serverUrl}}{{item.path}}" style='width:300px' id="myAudio" controls loop></audio>
            <radio style='margin-top:20px;' value='{{item.id}}'></radio>
            </view>
          </block>

        </radio-group>

        <view class="inputView">
            <label class="loginLabel">視頻描述:</label>
            <input name="desc" class="inputText" placeholder="說點什麼吧" />
        </view>

        <!-- 提交 -->
        <button class="submitBtn" type="primary" form-type='submit'>上傳視頻</button>

        <button class="gobackBtn" type="warn" form-type='reset'>重置</button>
    </form>
</view>
複製代碼
  • chooseBgm.js
const app = getApp()

Page({
    data: {
      poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
      name: '此時此刻',
      author: '許巍',
      src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
      serverUrl:"",
      videoParams:{}
    },
    onLoad:function(params){
      var me = this;
      console.log(params);

      me.setData({
        videoParams:params
      })

      wx.showLoading({
        title: '請等待...',
      });
      var serverUrl = app.serverUrl;
      // 調用後端
      wx.request({
        url: serverUrl + '/bgm/list',
        method: "POST",
        header: {
          'content-type': 'application/json', // 默認值
        },
        success: function (res) {
          console.log(res.data);
          wx.hideLoading();
          if (res.data.status == 200) {
            var bgmList = res.data.data;
            me.setData({
              bgmList: bgmList,
              serverUrl: serverUrl
            });
          } else if (res.data.status == 502) {
            wx.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: "none",
              success: function () {
                wx.redirectTo({
                  url: '../userLogin/login',
                })
              }
            });
          }
        }
      })
    },
  upload:function(e){
    var me = this;
    var datasParams = me.data.videoParams;
    var bgmId = e.detail.value.bgmId;
    var desc = e.detail.value.desc;
    console.log("bgmId:"+bgmId);
    console.log("desc:" + desc);
    var tempDuration = datasParams.tempDuration;
    var tempHeight = datasParams.tempHeight;
    var tempWidth = datasParams.tempWidth;
    var tempSize = datasParams.tempSize;
    var tempFilePath = datasParams.tempFilePath;
    var thumbTempFilePath = datasParams.thumbTempFilePath;
    var userId = app.userInfo.id;


    debugger;
    wx.showLoading({
      title: '請等待...',
    });
    var serverUrl = app.serverUrl;
    // 調用後端
   wx.uploadFile({
     url: serverUrl + '/video/upload',
     filePath: tempFilePath,
     formData:{
       userId: userId,
       bgmId: bgmId,
       videoSeconds: tempDuration,
       videoWidth: tempWidth,
       videoHeight: tempHeight,
       desc: desc,
     },
     name: 'file',
     success:function(res){
      console.log(res);
       wx.hideLoading();
     }

   })
  }
})


複製代碼

後端開發

後端接口在一個服務器上,後端的web在一臺服務器上。後端的web上傳小程序,須要同步到後端接口所在的一個服務器上。咱們選擇zokeeper。後邊會講git

  • service中添加

BgmService.javagithub

package com.idig8.service;

import java.util.List;

import com.idig8.pojo.Bgm;

public interface BgmService {

    /**
     * 獲取全部的Bgm列表
     * @return
     */
    public List<Bgm> queryBgmList();
}   
複製代碼

BgmServiceImpl.javaweb

package com.idig8.service.Impl;

import java.util.List;

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.idig8.mapper.BgmMapper;
import com.idig8.pojo.Bgm;
import com.idig8.service.BgmService;

@Service
public class BgmServiceImpl implements BgmService {

    @Autowired
    private BgmMapper bgmMapper;


    @Transactional(propagation =Propagation.SUPPORTS)
    @Override
    public List<Bgm> queryBgmList(){

        return bgmMapper.selectAll();
    }

}

複製代碼

BgmController.javaspring

package com.idig8.controller;

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.RestController;

import com.idig8.service.BgmService;
import com.idig8.utils.JSONResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value="背景音樂接口",tags={"背景音樂接口的controller"})
@RequestMapping(value = "/bgm")
public class BgmController extends BasicController{

    @Autowired
    private BgmService bgmService;



    @ApiOperation(value="獲取全部背景音樂",notes="經過獲取全部背景音樂")
    @PostMapping("/list")
    public JSONResult list() {
        return JSONResult.ok(bgmService.queryBgmList());
    }


}

複製代碼

接口已經在swagger驗證經過。json

小程序開發環境中會報net::ERR_INSUFFICIENT_RESOURCES這個錯誤,在真機中,不會出現該錯誤,忽略便可。小程序

PS:經過我的頁面傳遞視頻信息,到開發新界面背景音樂和描述,最後到文件信息上傳到後臺功能已經開發完畢。後端

相關文章
相關標籤/搜索