A正确
start()
函数如下所示:
function start() {
// create an object, an instance of the MediaSource
var mediaSource = new MediaSource;
// to this `mediaSource` object add an event listener for the `sourceopen` event
// and run the code inside the function when `sourceopen` happens
mediaSource.addEventListener('sourceopen', function () {
console.log('1');
var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
fetchAB(assetURL, function (buf) {
sourceBuffer.appendBuffer(buf);
});
});
// hey, `video` element, here is the source of the media I'd like you to play
// it's not a simple url, is something more complex
// , a `MediaSource` kind of thing
// and it might take you some time to be ready
video.src = URL.createObjectURL(mediaSource);
}
现在,回到整个代码。。。,如果您告诉浏览器执行以下行:
console.log('2');
,浏览器立即执行此操作没有问题,您将看到
2
立即在控制台中。
但是,这件事:
video.src = URL.createObjectURL(mediaSource);
对于浏览器来说并不是那么简单。
当您要求浏览器执行此操作时,浏览器是这样说的:“好吧,你让我执行,我现在就开始,你可以继续剩下的代码,但是,这一个对我来说并不那么容易……,我需要开始旋转一些轮子……,这将需要我一些时间……,而且,我不想在我准备好之前出去拿视频。我准备好后会告诉你。
事实上,不是直接的我,浏览器,而是
mediaSource
对象,它是
MediaSource
这是我的(
浏览器的
)API,将通过提出
sourceopen
事件
所以将此代码放在页面上时:
mediaSource.addEventListener('sourceopen', function () {
// do things
});
您正在告诉浏览器准备就绪时要做什么
源打开
已启动。
让我们总结一下:
12| start();
// start() is called and starts to execute but it has something inside that
// will take some time before ready
// as consequence `console.log('1')` does not happen yet
13| console.log('2');
// runs imediatelly
// you see "2" in the console
。。。一些时间过去了,代码在里面
开始()
正在准备东西
// the `sourceopen` event fires and a `function ()`
// the callback of `mediaSource.addEventListener('sourceopen'`
// starts to execute
21| console.log('1');
// gets executed
// you see "1" in the console