webrtc/public/music.js

112 lines
3.3 KiB
JavaScript
Raw Normal View History

2023-09-28 15:20:02 +08:00
import IndexedDB from './database.js'
import { Button, List, ListItem } from './weigets.js'
export default class MusicList {
constructor() {
2023-09-28 17:59:23 +08:00
this.EventListeners = {}
2023-09-28 15:20:02 +08:00
this.ul = List({})
this.store = new IndexedDB('musicDatabase', 1, 'musicObjectStore')
this.store.open().then(() => {
this.store.getAll().then((data) => {
2023-09-28 23:49:26 +08:00
data.forEach(item => this.__add(item))
2023-09-28 15:20:02 +08:00
})
})
document.body.appendChild(this.ul)
// 添加音乐播放器
this.audio = new Audio()
this.audio.addEventListener('ended', () => {
this.next()
})
2023-09-28 17:59:23 +08:00
//this.audio.addEventListener('timeupdate', () => {
// console.log(this.audio.currentTime)
//})
2023-09-28 15:20:02 +08:00
// 添加音乐按钮
const input = document.createElement('input')
input.type = 'file'
input.multiple = true
input.accept = 'audio/*'
input.onchange = event => {
for (const file of event.target.files) {
2023-09-28 18:15:12 +08:00
const id = 'music' + Date.now()
2023-09-28 15:20:02 +08:00
const { name, size, type } = file
const reader = new FileReader()
reader.onload = async event => {
const arrayBuffer = event.target.result
this.add({ id, name, size, type, arrayBuffer })
}
reader.readAsArrayBuffer(file)
}
}
document.body.appendChild(input)
}
2023-09-28 23:49:26 +08:00
// 仅添加UI
__add(item) {
2023-09-28 15:20:02 +08:00
const li = ListItem({
id: item.id,
innerText: `${item.name} - ${item.size} - ${item.type} - ${item.id}`,
onclick: event => {
event.stopPropagation()
2023-09-28 17:59:23 +08:00
this.play(item)
2023-09-28 15:20:02 +08:00
},
children: [
Button({
innerText: '播放',
onclick: event => {
event.stopPropagation()
2023-09-28 17:59:23 +08:00
this.play(item)
2023-09-28 15:20:02 +08:00
}
}),
Button({
innerText: '停止',
onclick: event => {
event.stopPropagation()
this.stop(item.id)
}
}),
Button({
innerText: '移除',
onclick: event => {
event.stopPropagation()
2023-09-28 17:59:23 +08:00
this.delete(item)
2023-09-28 15:20:02 +08:00
}
})
]
})
this.ul.appendChild(li)
}
2023-09-28 23:49:26 +08:00
// 添加数据并添加UI
add(item) {
this.store.add(item)
this.__add(item)
}
2023-09-28 17:59:23 +08:00
delete(item) {
this.store.delete(item.id)
this.ul.removeChild(this.ul.querySelector(`#${item.id}`))
this.stop() // 停止播放
}
play(item) {
this.audio.src = URL.createObjectURL(new Blob([item.arrayBuffer], { type: item.type }))
this.audio.play()
this._on('play', item)
}
stop() {
this.audio.pause()
this.audio.src = ''
this._on('stop')
2023-09-28 15:20:02 +08:00
}
next() { }
prev() { }
2023-09-28 17:59:23 +08:00
// 添加回调函数
on(name, callback) {
this.EventListeners[name] = callback
}
// 执行回调函数
_on(name, ...args) {
if (this.EventListeners[name]) {
this.EventListeners[name](...args)
}
}
2023-09-28 15:20:02 +08:00
}