indexedDB 缓存

This commit is contained in:
2023-09-28 01:14:49 +08:00
parent 9105ee0108
commit 0e6bc7ddf7
2 changed files with 160 additions and 4 deletions

102
public/database.js Normal file
View File

@ -0,0 +1,102 @@
// 使用示例:
// const db = new IndexedDB('myDatabase', 1, 'myStore');
// await db.open();
// await db.add({ id: 1, name: 'John' });
// const data = await db.get(1);
// console.log(data);
// await db.delete(1);
export default class IndexedDB {
constructor(databaseName, databaseVersion, storeName) {
this.databaseName = databaseName;
this.databaseVersion = databaseVersion;
this.storeName = storeName;
this.db = null;
}
open() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.databaseName, this.databaseVersion);
request.onerror = (event) => {
reject(event.target.error);
};
request.onsuccess = (event) => {
this.db = event.target.result;
resolve(this.db);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains(this.storeName)) {
db.createObjectStore(this.storeName, { keyPath: 'id' });
}
};
});
}
add(data) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readwrite');
const objectStore = transaction.objectStore(this.storeName);
const request = objectStore.add(data);
request.onerror = (event) => {
reject(event.target.error);
};
request.onsuccess = (event) => {
resolve(event.target.result);
};
});
}
get(id) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readonly');
const objectStore = transaction.objectStore(this.storeName);
const request = objectStore.get(id);
request.onerror = (event) => {
reject(event.target.error);
};
request.onsuccess = (event) => {
resolve(event.target.result);
};
});
}
getAll() {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readonly');
const objectStore = transaction.objectStore(this.storeName);
const request = objectStore.getAll();
request.onerror = (event) => {
reject(event.target.error);
};
request.onsuccess = (event) => {
resolve(event.target.result);
};
});
}
delete(id) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readwrite');
const objectStore = transaction.objectStore(this.storeName);
const request = objectStore.delete(id);
request.onerror = (event) => {
reject(event.target.error);
};
request.onsuccess = (event) => {
resolve(event.target.result);
};
});
}
}

View File

@ -12,15 +12,21 @@
<p>message</p> <p>message</p>
</div> </div>
<script type="module"> <script type="module">
import IndexedDB from './database.js'
const musicObjectStore = new IndexedDB('musicDatabase', 1, 'musicObjectStore')
await musicObjectStore.open()
// webRTC 传递音乐(分别传输文件和操作事件能更流畅) // webRTC 传递音乐(分别传输文件和操作事件能更流畅)
const music = async function () { const music = async function () {
const clients = [] // 客户端列表
const ul = document.createElement('ul') const ul = document.createElement('ul')
document.body.appendChild(ul) document.body.appendChild(ul)
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws' const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
const host = window.location.host const host = window.location.host
const ws = new WebSocket(`${protocol}://${host}/webrtc/music`) const ws = new WebSocket(`${protocol}://${host}/webrtc/music`)
const pc = new RTCPeerConnection() const pc = new RTCPeerConnection()
const clients = []
// 监听 ICE 候选事件 // 监听 ICE 候选事件
pc.onicecandidate = event => { pc.onicecandidate = event => {
if (event.candidate) { if (event.candidate) {
@ -93,18 +99,66 @@
return return
} }
} }
// 从数据库读取音乐文件
musicObjectStore.getAll().then(data => {
console.log('从数据库读取音乐文件', data)
const ol = document.createElement('ol')
data.forEach(item => {
const li = document.createElement('li')
li.innerText = `${item.name} - ${item.size} - ${item.type} - ${item.id}`
const start = document.createElement('button')
start.innerText = '播放'
start.onclick = async () => {
console.log('播放音乐', item)
// 传输音乐文件
const arrayBuffer = item.arrayBuffer
const audioContext = new AudioContext()
audioContext.decodeAudioData(arrayBuffer, async audioBuffer => {
// 将音乐流添加到 RTCPeerConnection
const mediaStreamDestination = audioContext.createMediaStreamDestination()
mediaStreamDestination.stream.getAudioTracks().forEach(function (track) {
pc.addTrack(track, mediaStreamDestination.stream)
})
// 播放音乐
const audioSource = audioContext.createBufferSource()
audioSource.buffer = audioBuffer
audioSource.connect(mediaStreamDestination)
audioSource.start()
// 创建SDP offer并将其设置为本地描述, 发送给远程端
console.log('创建SDP offer并将其设置为本地描述, 发送给远程端')
console.log('clients:', clients)
const id = clients[0].id
await pc.setLocalDescription(await pc.createOffer()) // 设置本地描述为 offer
ws.send(JSON.stringify({ id, offer: pc.localDescription })) // 发送给远程终端 offer
})
}
li.appendChild(start)
const remove = document.createElement('button')
remove.innerText = '移除'
remove.onclick = async () => {
await musicObjectStore.delete(item.id)
li.remove()
}
li.appendChild(remove)
ol.appendChild(li)
})
document.body.appendChild(ol)
})
// 从文件系统中选择音乐文件 // 从文件系统中选择音乐文件
const button = document.createElement('button') const button = document.createElement('button')
button.innerText = '选择音乐' button.innerText = '选择音乐'
button.addEventListener('click', async () => { button.addEventListener('click', async () => {
const id = Date.now()
const fileHandle = await window.showOpenFilePicker() const fileHandle = await window.showOpenFilePicker()
const file = await fileHandle[0].getFile() const file = await fileHandle[0].getFile()
const { name, size, type, lastModified, lastModifiedDate } = file
const reader = new FileReader() const reader = new FileReader()
reader.onload = function () { reader.onload = async () => {
console.log('read file:', file)
const arrayBuffer = reader.result const arrayBuffer = reader.result
const audioContext = new AudioContext() // 存储到 IndexDB
musicObjectStore.add({ id, name, size, type, lastModified, lastModifiedDate, arrayBuffer })
// 传输音乐文件 // 传输音乐文件
const audioContext = new AudioContext()
audioContext.decodeAudioData(arrayBuffer, async audioBuffer => { audioContext.decodeAudioData(arrayBuffer, async audioBuffer => {
// 将音乐流添加到 RTCPeerConnection // 将音乐流添加到 RTCPeerConnection
const mediaStreamDestination = audioContext.createMediaStreamDestination() const mediaStreamDestination = audioContext.createMediaStreamDestination()