73 lines
1.4 KiB
JavaScript
73 lines
1.4 KiB
JavaScript
bricks = window.bricks || {};
|
|
|
|
bricks.UpStreaming = class extends bricks.JsWidget {
|
|
/*
|
|
{
|
|
"url":
|
|
}
|
|
*/
|
|
constructor(opts){
|
|
super(opts);
|
|
}
|
|
async go(){
|
|
this.body = new ReadableStream(this);
|
|
this.headers = new Headers();
|
|
this.headers.append('Content-Type',
|
|
'application/octet-stream');
|
|
var resp = await fetch(this.url, {
|
|
method: 'POST',
|
|
headers: this.headers,
|
|
duplex: 'full',
|
|
body: this.body
|
|
});
|
|
return resp
|
|
}
|
|
send(data){
|
|
this.stream_ctlr.enqueue(data);
|
|
}
|
|
finish(){
|
|
this.stream_ctlr.close();
|
|
}
|
|
start(controller){
|
|
this.stream_ctlr = controller;
|
|
}
|
|
}
|
|
|
|
bricks.down_streaming = function(widget, response) {
|
|
const reader = response.body.getReader();
|
|
new ReadableStream({
|
|
start(controller) {
|
|
function push() {
|
|
// 读取下一个数据块
|
|
reader.read().then(({ done, value }) => {
|
|
if (done) {
|
|
// 如果读取完成,关闭流
|
|
controller.close();
|
|
return;
|
|
}
|
|
// 将数据块放入队列
|
|
controller.enqueue(value);
|
|
push();
|
|
}).catch(error => {
|
|
console.error('Error reading data', error);
|
|
controller.error(error);
|
|
});
|
|
}
|
|
push();
|
|
}
|
|
})
|
|
.then(stream => {
|
|
// 将ReadableStream转换为Blob
|
|
return new Response(stream).blob();
|
|
})
|
|
.then(blob => {
|
|
const audioSrc = widget.set_url(URL.createObjectURL(blob));
|
|
widget.bind('canplay', () => {
|
|
widget.play();
|
|
});
|
|
})
|
|
.catch(error => {
|
|
console.error('Fetching audio stream failed', error);
|
|
});
|
|
}
|