VideoPreviewPlayer.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <template>
  2. <div id="dplayer" ref="dplayer" style="height: 480px;" />
  3. </template>
  4. <script>
  5. import { videoUrl } from '@/api/video'
  6. import flvjs from 'flv.js'
  7. import DPlayer from 'dplayer'
  8. export default {
  9. name: 'VideoPreviewPlayer',
  10. props: {
  11. videoProp: {
  12. type: Object,
  13. default: () => null
  14. }
  15. },
  16. data() {
  17. return {
  18. flvjs,
  19. DPlayer,
  20. message: '',
  21. dplayer: null
  22. }
  23. },
  24. watch: {
  25. // 监控 videoProp 对象的变化
  26. videoProp(newVal) {
  27. console.log('videoProp changed')
  28. if (!newVal.play) {
  29. this.dplayer.destroy()
  30. } else {
  31. this.getVideoUrl(newVal.videoId)
  32. }
  33. }
  34. },
  35. created() {
  36. this.getVideoUrl(this.videoProp.videoId)
  37. },
  38. methods: {
  39. getVideoUrl(videoId) {
  40. videoUrl(videoId).then(res => {
  41. if (res.code === 0) {
  42. const urlType = res.data.type
  43. if (urlType === 'mp4') {
  44. const urls = res.data.urls
  45. for (const url of urls) {
  46. url.type = 'normal'
  47. }
  48. this.dplayer = this.initMp4Player(this.videoProp.coverUrl, urls)
  49. } else if (urlType === 'flv') {
  50. const urls = res.data.urls
  51. const url = urls[0].url
  52. this.dplayer = this.initFlvPlayer(this.videoProp.coverUrl, url)
  53. } else {
  54. this.message = 'url 类型无法识别'
  55. }
  56. } else {
  57. console.error(res.msg)
  58. }
  59. }).catch(error => {
  60. console.error(error.message)
  61. })
  62. },
  63. initMp4Player(coverUrl, videoUrls) {
  64. return new DPlayer({
  65. container: document.querySelector('#dplayer'),
  66. lang: 'zh-cn',
  67. screenshot: false,
  68. autoplay: true,
  69. volume: 0.1,
  70. mutex: true,
  71. video: {
  72. pic: coverUrl,
  73. defaultQuality: 0,
  74. quality: videoUrls
  75. }
  76. })
  77. },
  78. initFlvPlayer(coverUrl, videoUrl) {
  79. return new DPlayer({
  80. container: document.getElementById('dplayer'),
  81. video: {
  82. url: videoUrl,
  83. type: 'customFlv',
  84. customType: {
  85. customFlv: function(video, player) {
  86. const flvPlayer = flvjs.createPlayer({
  87. type: 'flv',
  88. url: video.src
  89. })
  90. flvPlayer.attachMediaElement(video)
  91. flvPlayer.load()
  92. }
  93. }
  94. }
  95. })
  96. }
  97. }
  98. }
  99. </script>
  100. <style>
  101. </style>