Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

svelte项目引入之后提示window is not defined #79

Open
v423 opened this issue May 8, 2023 · 0 comments
Open

svelte项目引入之后提示window is not defined #79

v423 opened this issue May 8, 2023 · 0 comments

Comments

@v423
Copy link

v423 commented May 8, 2023

自问自答做个备注

svelte默认开启服务端渲染, 在server端window不可用, 因此会出现标题报错
通常可以通过引入browser环境属性判断是否在客户端 if(browser){ xxxx }
但是import语句需要在顶层使用, 所以没法通过if判断browser规避问题(也可能可以通过动态组件实现动态渲染?)
因此通过在onMount中渲染来解决, onMount中也有import导入的问题, 需要通过await import解决顶层问题

<script lang="ts">
	import { onMount } from 'svelte';

	let amr, play;
	let isPlaying = false;
	let position = '0.00';
	let duration = '0.00';
	let interval = 0;
	export let url = 'amr_file_url';

	onMount(async () => {
		const { default: BenzAMRRecorder } = await import('benz-amr-recorder');
		amr = new BenzAMRRecorder();
		await amr.initWithUrl(url); // 需要await阻塞 否则duration拿不到 或者添加到init的回调也可以

		duration = amr.getDuration().toFixed(2);
		play = () => {
			amr.playOrPauseOrResume();
			isPlaying = !isPlaying;
			if (isPlaying && !interval) {
				interval = setInterval(() => {
					position = amr.getCurrentPosition().toFixed(2);
				}, 1000);
			}
		};
		amr.onEnded(() => {
			isPlaying = false;
			position = '0.00';
			clearInterval(interval);
		});
	});
	function download(url){  }
</script>

<button size="sm" on:click={play}>{isPlaying ? '暂停' : '播放'}</button>
<button size="sm" on:click={() => download(url)}>下载</button>
<div class="mt-2">进度: {position}s / {duration}s</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant