播放页面

    1. <Back/>
    2. <div>
    3. <button on:click="next()">next</button>
    4. <button on:click="prev()">prev</button>
    5. <button on:click="file()">file</button>
    6. </div>
    7. <script>
    8. import {
    9. ipcRenderer,
    10. remote
    11. } from "electron";
    12. const {
    13. dialog,
    14. app
    15. } = remote
    16. const {
    17. readdir
    18. } = remote.require('fs-extra')
    19. import {
    20. resolve
    21. } from 'path'
    22. export default {
    23. data() {
    24. return {
    25. currentSrc: '',
    26. index: 0,
    27. files: []
    28. };
    29. },
    30. components: {
    31. Back: '../components/Back.svelte'
    32. },
    33. document.querySelector('#app').appendChild(this.player)
    34. this.player.onended = this.next // 播放完成下一首
    35. this.on('state', ({
    36. changed
    37. }) => {
    38. if (changed.currentSrc) {
    39. this.player.src = this.get().currentSrc
    40. this.play()
    41. }
    42. })
    43. },
    44. methods: {
    45. next() { // 下一曲
    46. const {
    47. index,
    48. files
    49. } = this.get()
    50. let i = index + 1
    51. if (i > files.length - 1) { // 边界守护
    52. i = files.length - 1
    53. }
    54. this.set({
    55. index: i,
    56. currentSrc: "file://" + files[i]
    57. })
    58. },
    59. prev() { // 上一曲
    60. const {
    61. index,
    62. files
    63. } = this.get()
    64. let i = index - 1
    65. if (i < 0) { // 边界守护
    66. i = 0
    67. }
    68. index: i,
    69. currentSrc: "file://" + files[i]
    70. })
    71. },
    72. play() { // 播放
    73. this.player.play()
    74. },
    75. pause() { // 暂停
    76. this.play.pause()
    77. },
    78. file() { // 选取文件
    79. dialog.showOpenDialog({
    80. title: '选择音乐目录',
    81. defaultPath: app.getPath('home'),
    82. properties: ['openDirectory']
    83. }, async(folders) => {
    84. if (folders.length > 0) {
    85. const folder = folders[0]
    86. let files = await readdir(folder)
    87. const compare = (a, b) => { // 比较字符串前面的数字
    88. let t1 = a.split('-')[0];
    89. let t2 = b.split('-');
    90. return parseInt(t1) - parseInt(t2)
    91. }
    92. files = files.sort(compare).map(file => resolve(folder, file)) // 文件排序
    93. this.set({
    94. files,
    95. currentSrc: "file://" + files[0]
    96. })
    97. }
    98. })
    99. }
    100. }