media-container.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. Page({
  2. onShareAppMessage() {
  3. return {
  4. title: '音视频合成',
  5. path: 'packageAPI/pages/media/media-container/media-container'
  6. }
  7. },
  8. onLoad() {
  9. this.setData({
  10. theme: wx.getSystemInfoSync().theme || 'light'
  11. })
  12. if (wx.onThemeChange) {
  13. wx.onThemeChange(({theme}) => {
  14. this.setData({theme})
  15. })
  16. }
  17. const canIUse = wx.canIUse('wx.createMediaContainer()')
  18. if (canIUse) {
  19. this.mediaContainer = wx.createMediaContainer()
  20. } else {
  21. this.setData({
  22. canIUse: false,
  23. })
  24. wx.showModal({
  25. title: '微信版本过低,暂不支持本功能',
  26. })
  27. }
  28. },
  29. data: {
  30. theme: 'light',
  31. targetSrc: '',
  32. one: '',
  33. two: '',
  34. canIUse: true,
  35. },
  36. handleChooseVideo(e) {
  37. const that = this
  38. wx.chooseVideo({
  39. sourceType: ['album', 'camera'],
  40. success(res) {
  41. console.log(res.tempFilePath)
  42. that.setData({
  43. [e.currentTarget.dataset.video]: res.tempFilePath
  44. })
  45. if (e.currentTarget.dataset.video === 'one') {
  46. that.mediaContainer.extractDataSource({
  47. source: that.data.one,
  48. success(mt) {
  49. that.mediaTrackOne = mt
  50. }
  51. })
  52. } else {
  53. that.mediaContainer.extractDataSource({
  54. source: that.data.two,
  55. success(mt) {
  56. that.mediaTrackTwo = mt
  57. }
  58. })
  59. }
  60. }
  61. })
  62. },
  63. handleExport() {
  64. if (this.data.one === '' || this.data.two === '') {
  65. wx.showToast({
  66. title: '请先选择源视频',
  67. icon: 'none'
  68. })
  69. } else {
  70. console.log(this.mediaTrackOne, this.mediaTrackTwo)
  71. // 获取源视频 1 的视频轨道
  72. const [trackMedia] = this.mediaTrackOne.tracks.filter(item => item.kind === 'video')
  73. // 获取源视频 2 的音频轨道
  74. const [trackAudio] = this.mediaTrackTwo.tracks.filter(item => item.kind === 'audio')
  75. console.log(trackMedia, trackAudio)
  76. // 添加轨道到目标容器
  77. this.mediaContainer.addTrack(
  78. trackMedia
  79. )
  80. this.mediaContainer.addTrack(
  81. trackAudio
  82. )
  83. const that = this
  84. // 合成目标视频
  85. this.mediaContainer.export({
  86. success: (res) => {
  87. that.setData({
  88. targetSrc: res.tempFilePath
  89. })
  90. }
  91. })
  92. }
  93. }
  94. })