유니 코드

[Android] 뽀모도로 타이머 만들기 with 코틀린(3) - 효과음 넣기(SoundPool 사용) 본문

오늘의 공부는?!/Android

[Android] 뽀모도로 타이머 만들기 with 코틀린(3) - 효과음 넣기(SoundPool 사용)

꼬물쥰 2022. 2. 21. 20:01
SoundPool

공식문서

오디오 사운드를 재생하고 관리하는 클래스로

오디오 파일을 메모리에 로드한 후 비교적 빠르게 재생할 수 있도록 도와줌

되도록이면 짧은 영상만 재생할 수 있게 제약이 걸려있음

 

효과음 넣기

private val soundPool = SoundPool.Builder().build()
    
private var tickingSoundId: Int? = null
private var bellSoundId: Int? = null

soundPool과 사운드Id를 지정해줄 변수 선언한다.

 

private fun initSounds(){
    tickingSoundId = soundPool.load(this, R.raw.timer_ticking, 1)
    bellSoundId = soundPool.load(this, R.raw.timer_bell, 1)
}

소리를 불러오는 initSounds() 생성한다. 

타이머가 실행될 때 들리는 ticking소리와 완료되었을 때 울리는 bell소리를

soundPool을 이용하여 load해온다.

이 때, load()는 load해온 사운드Id를 반환하기 때문에 위에서 선언한 변수들에 넣어준다.

 

private fun startCountDown(){
    currentCountDownTimer = createCountDownTimer(seekBar.progress * 60 * 1000L)
    currentCountDownTimer?.start()

    tickingSoundId?.let {soundId ->
        soundPool.play(soundId,1F, 1F, 0, -1, 1F)
    }
}

카운트다운이 시작되었을 때 효과음을 실행해주는 함수를 생성한다.

인자로 전달해야할 property가 nullable할 때, property가 null이 아니면 let을 호출하여 soundId로 해당 값을 전달한다.

그리고 그 값을 바로 인자로 전달하는 코드이다.

 

생명주기에 따른 사운드 관리
override fun onResume() {
    super.onResume()
    soundPool.autoResume()
}

override fun onPause() {
    super.onPause()
    soundPool.autoPause()
}

override fun onDestroy() {
    super.onDestroy()
    soundPool.release()
}

onPause() - 화면에 앱이 보이지 않는 경우 실행(모든 사운드가 정지되도록 설정)

onResume() - 앱이 다시 실행될 경우 실행(사운드 재생되도록 설정)

onDestroy() - 앱이 완전히 종료되었을 경우 실행(사운드를 release시켜 메모리에서 해제)

 

여기까지 기본 UI만 설정한 후에 타이머기능, 효과음 기능을 추가하였다.

 

플 완성도 높이기

뽀모도로 타이머인만큼 어플UI를 토마토 모양으로 수정해보았다.

theme.xml을 수정하여 windowBackground색을 미리 설정해놓은 토마토색으로 변경하였고,

액션바도 제거하였다.

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.Pomodoro" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Status bar color. -->
        <item name="android:statusBarColor" >@color/pomodoro_red</item>
        <!-- Customize your theme here. -->
        <item name="android:windowBackground">@color/pomodoro_red</item>
    </style>
</resources>

 

또한 텍스트뷰 위에 토마토 꼭지모양의 이미지뷰를 추가해주었다.

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/img_tomato_stem"
    app:layout_constraintBottom_toTopOf="@id/remainMinutesTextView"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

 

이외에도 seekBar의 tickMark와 thumb을 수정하여 seekBar 디자인을 변경하였다.

 

결과화면

 

Comments