개발 창고/Android

[Kotlin] "Ringtone" 사용하는 방법

로이제로 2023. 7. 20. 22:00
반응형

1. Ringtone 객체 생성

class RingtoneActivity : AppCompatActivity() {
    private var ringtone : Ringtone? = null
    ...
}

Ringtone에 사용될 객체를 선언합니다.

 

2. Ringtone 실행

/**
 * @description 벨소리 시작
 * @param   context     컨텍스트
 * @param   packageName 패키지 명 (ex. com.test.app)
 * @param   path        벨소리 경로 (test.mp3)
 */
fun startRingtone(context:Context, packageName:String, path:String){
    // 사전에 선언된 벨소리가 있는 경우 중지
    if(ringtone != null)   ringtone!!.stop()

    val uriString       = "android.resource://${packageName}/raw/${path}"
    val uriRingtone     = Uri.parse(uriString)
    ringtone            = RingtoneManager.getRingtone(context, uriRingtone)

    ringtone!!.play()
}

아래와 같이 resource폴더의 raw폴더에 포함된 ringtone을 호출하게 되는데

현재 앱의 패키지가 com.test.app이고, 재생하려는 ringtone이 fantasy_alarm_clock.mp3인 경우 아래와 같이 호출하면 rintone이 재생됩니다.

startRingtone(this, "com.test.app", "fantasy_alarm_clock.mp3")

 

3. Ringtone 중지

/**
 * @description 벨소리 중지
 */
fun stopRingtone(){
    if(ringtone != null){
        ringtone!!.stop()
        ringtone = null
    }
}

사전에 선언된 Ringtone이 있는 경우에만 재생을 중지하고 객체를 비워줍니다.

 

※ 이 글은 워드프레스에 작성한 글과 동일한 작성자의 동일한 글입니다.

https://royfactory.net/2023/06/29/kotlin-ringtone-use/

 

[Kotlin] How to use “Ringtone” - ROY FACTORY

What are some ways to control ringtone in Kotlin? Let's find out about Ringtone, which can be used to create alarms or give notifications.

royfactory.net

 

반응형