본문 바로가기
안드로이드 코틀린

[Kotlin][Android] 음악 재생 예시 만들기

by teamnova 2025. 3. 22.
728x90

오늘은 사전에 앱에 저장해둔 음악 파일을 재생하는 예시를 만들어 보겠습니다.

 

 

재생할 음악 파일 준비

=> 위 이미지와 같이 앱의 res 폴더 내에 raw 폴더 생성 후 재생할 음악 파일을 저장시켜 주세요

 

 

 

레이아웃 xml 파일 코드(activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/titleTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="음악 재생 예시"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="32dp" />

    <ImageView
        android:id="@+id/musicIconImageView"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:src="@android:drawable/ic_media_play"
        app:layout_constraintTop_toBottomOf="@id/titleTextView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="64dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        app:layout_constraintTop_toBottomOf="@id/musicIconImageView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="64dp">

        <Button
            android:id="@+id/playButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="재생"
            android:layout_margin="8dp" />

        <Button
            android:id="@+id/pauseButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="일시정지"
            android:layout_margin="8dp" />

        <Button
            android:id="@+id/stopButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="정지"
            android:layout_margin="8dp" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

 

 

 

 

액티비티 코틀린 코드

class MainActivity : AppCompatActivity() {

    private lateinit var playButton: Button    // 재생 버튼
    private lateinit var pauseButton: Button   // 일시정지 버튼
    private lateinit var stopButton: Button    // 정지 버튼

    // MediaPlayer 객체 - null로 초기화하여 필요할 때만 메모리 할당
    private var mediaPlayer: MediaPlayer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        playButton = findViewById(R.id.playButton)
        pauseButton = findViewById(R.id.pauseButton)
        stopButton = findViewById(R.id.stopButton)

        // 각 버튼에 클릭 이벤트 리스너 설정
        playButton.setOnClickListener {
            playMusic()  // 재생 버튼 클릭 시 음악 재생 메서드 호출
        }

        pauseButton.setOnClickListener {
            pauseMusic()  // 일시정지 버튼 클릭 시 일시정지 메서드 호출
        }

        stopButton.setOnClickListener {
            stopMusic()  // 정지 버튼 클릭 시 정지 메서드 호출
        }
    }

    // 음악 재생 메서드
    private fun playMusic() {
        if (mediaPlayer == null) {
            // MediaPlayer가 아직 초기화되지 않았으면 초기화
            mediaPlayer = MediaPlayer.create(this, R.raw.sample)

            // 음악 재생이 완료되었을 때 실행할 리스너 설정
            mediaPlayer?.setOnCompletionListener {
                Toast.makeText(this, "재생 완료", Toast.LENGTH_SHORT).show()
                stopMusic()  // 재생 완료 시 정지 메서드 호출하여 리소스 정리
            }
        }

        // 음악 재생 시작
        mediaPlayer?.start()
        // 사용자에게 알림 표시
        Toast.makeText(this, "음악 재생", Toast.LENGTH_SHORT).show()
    }

    // 음악 일시정지 메서드
    private fun pauseMusic() {
        // 현재 재생 중인 경우에만 일시정지 실행
        if (mediaPlayer?.isPlaying == true) {
            mediaPlayer?.pause()
            Toast.makeText(this, "일시 정지", Toast.LENGTH_SHORT).show()
        }
    }

    // 음악 정지 메서드
    private fun stopMusic() {
        if (mediaPlayer != null) {
            mediaPlayer?.stop()     // 재생 중지
            mediaPlayer?.release()  // 리소스 해제(메모리 누수 관리)
            mediaPlayer = null      // 변수를 null로 설정하여 재사용 시 새로 초기화
            Toast.makeText(this, "정지", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 액티비티가 소멸될 때 MediaPlayer 리소스 해제
        // 메모리 누수 방지 단계
        if (mediaPlayer != null) {
            mediaPlayer?.release()
            mediaPlayer = null
        }
    }
}

 

 

 

 

실행 결과

 

 

음악이 재생되는 것을 확인할 수 있습니다