播放页面
<Back/>
<div>
<button on:click="next()">next</button>
<button on:click="prev()">prev</button>
<button on:click="file()">file</button>
</div>
<script>
import {
ipcRenderer,
remote
} from "electron";
const {
dialog,
app
} = remote
const {
readdir
} = remote.require('fs-extra')
import {
resolve
} from 'path'
export default {
data() {
return {
currentSrc: '',
index: 0,
files: []
};
},
components: {
Back: '../components/Back.svelte'
},
document.querySelector('#app').appendChild(this.player)
this.player.onended = this.next // 播放完成下一首
this.on('state', ({
changed
}) => {
if (changed.currentSrc) {
this.player.src = this.get().currentSrc
this.play()
}
})
},
methods: {
next() { // 下一曲
const {
index,
files
} = this.get()
let i = index + 1
if (i > files.length - 1) { // 边界守护
i = files.length - 1
}
this.set({
index: i,
currentSrc: "file://" + files[i]
})
},
prev() { // 上一曲
const {
index,
files
} = this.get()
let i = index - 1
if (i < 0) { // 边界守护
i = 0
}
index: i,
currentSrc: "file://" + files[i]
})
},
play() { // 播放
this.player.play()
},
pause() { // 暂停
this.play.pause()
},
file() { // 选取文件
dialog.showOpenDialog({
title: '选择音乐目录',
defaultPath: app.getPath('home'),
properties: ['openDirectory']
}, async(folders) => {
if (folders.length > 0) {
const folder = folders[0]
let files = await readdir(folder)
const compare = (a, b) => { // 比较字符串前面的数字
let t1 = a.split('-')[0];
let t2 = b.split('-');
return parseInt(t1) - parseInt(t2)
}
files = files.sort(compare).map(file => resolve(folder, file)) // 文件排序
this.set({
files,
currentSrc: "file://" + files[0]
})
}
})
}
}