본문 바로가기
개발일지/Web Development

[JavaScript] audio의 duration 구하기(재생시간)

by jungwonyu 2023. 9. 27.
728x90

1. audio를 생성한다.

    const tempSound = new Audio('../include/media/temp.mp3');

 

2. audio의 duration을 초깃값을 0을 넣어 변수로 선언한다.

 let tempSoundDuration = 0;

 

3. onloadedata를 통해 audio의 daration을 가져온다.

    tempSound.onloadeddata = () => {
      tempSoundDuration  = tempSound .duration;
    };

위와 같이 onloadedata를 사용하지 않고 tempSound.duration만 찍어봤을 때는 NaN이 나올 것이다.

데이터가 갱신되기 전이기 때문이다. 따라서 load된 뒤 가져오기 위해 onloadedata를 사용한다.

 

4. console.log를 통해 찍어본다. 잘나온다.

console.log(tempSoundDuration );