프로젝트/Springboot_MariaDB

[Springboot] 웹 브라우저에 음악 파일 재생하기

CBJH 2024. 5. 28.
728x90
반응형

1. 목적

  • Springboot에서 컨트롤러를 만들고 html에서 서버에 저장된 mp3파일을 재생한다.
  • (버튼 클릭 없이)1분마다 mp3파일을 재생한다.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sound Play Example</title>
</head>
<body>
<h1>MP3 파일 재생 테스트</h1>
<button onclick="playSound()">알람 소리 재생</button>
<script>
    function playSound() {
        const audio = new Audio('/alarm.mp3');
        audio.play();
    }

    document.addEventListener('DOMContentLoaded', function() {
        const audio = new Audio('/alarm.mp3');

        //알람 mp3를 실행, 화면에 alert를 띄워주는 함수
        function testPlay() {
            audio.play();
            alert("알람 시간입니다!");
        }

        setInterval(testPlay, 60000); //돔이 열리고 1분마다 testPlay함수를 실행합니다.
    });
</script>
</body>
</html>
  • new Audio('/alarm.mp3');
    • 인텔리제이 src/main/static/alarm.mp3 오디오 파일 객체 인스턴스를 생성한다.
  • audio.play();
    • 오디오를 실행한다.
  • setInterval(함수명, 시간);
    • 일정 시간마다 함수를 실행한다.
  • 이 코드를 실행해도 알람은 울리지 않는다. 
  • 알람 소리 재생 버튼을 누른 후 기다리면 1분마다 audio.mp3가 실행된다.
@Controller
public class Mp3testController {

    @GetMapping("/")
    public String testmp3() {
        return "mp3test";
    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}
  • /static 폴더에 있는 mp3 파일을 실행하기 위해 Configuration 어노테이션을 추가해준다.


2.  실행 화면

3. 시간 반환 함수

const hours = now.getHours().toString().padStart(2, '0');
  • now.getHours()는 현재 시간의 시간 부분(0-23)을 반환합니다.
  • toString() 메서드는 숫자를 문자열로 변환합니다.
  • padStart(2, '0')는 반환된 문자열의 길이가 2가 되도록 합니다. 만약 문자열의 길이가 이미 2 이상이면 아무런 변경도 하지 않습니다. 길이가 1인 경우 (즉, 시간이 0에서 9 사이인 경우)에는 문자열 앞에 '0'을 추가하여 두 자리 수로 만듭니다.

댓글