on
MediaPlayer(background, raw)
MediaPlayer(background, raw)
package com.example.mediaplayerraw import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val mp1 = findViewById(R.id.mp1) val mp2 = findViewById(R.id.mp2) val mp3 = findViewById(R.id.mp3) val pause = findViewById(R.id.pause) val stop = findViewById(R.id.stop) mp1.setOnClickListener { play(R.raw.mplong1) } mp2.setOnClickListener { play(R.raw.mplong2) } mp3.setOnClickListener { play(R.raw.mp3) } pause.setOnClickListener { pause() } stop.setOnClickListener { stop() } } private fun play(data : Int){ val intent= Intent(applicationContext, Service::class.java) intent.putExtra("data", data) applicationContext?.startService(intent) } private fun pause(){ val intent= Intent(applicationContext, Service::class.java) intent.putExtra("data", 0) applicationContext?.startService(intent) } private fun stop(){ val intent= Intent(applicationContext, Service::class.java) intent.putExtra("data", -1) applicationContext?.startService(intent) } }
package com.example.mediaplayerraw import android.app.Service import android.content.Intent import android.media.MediaPlayer import android.os.IBinder class Service : Service() { var mediaPlayer : MediaPlayer? = MediaPlayer() var pausePoint = 0 var data :Int = 0 override fun onBind(p0: Intent?): IBinder? { return null } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { data = intent?.getIntExtra("data",0) ?: 0 when(data){ -1 -> stop() 0 -> pause() else -> play(data) } // if(mediaPlayer?.isPlaying == true){ // Log.d("gayoung","뭔가 재생중") // } return super.onStartCommand(intent, flags, startId) } fun play(i :Int){ if(pausePoint == 0){ if(mediaPlayer != null){ mediaPlayer?.release() mediaPlayer = null } mediaPlayer = MediaPlayer.create(applicationContext, i) mediaPlayer?.start() mediaPlayer?.setOnCompletionListener { it.release() } }else{ mediaPlayer?.seekTo(pausePoint) mediaPlayer?.start() pausePoint = 0 } } fun pause(){ mediaPlayer?.pause() pausePoint = mediaPlayer?.currentPosition ?: 0 } fun stop(){ if(mediaPlayer != null){ mediaPlayer?.release() mediaPlayer = null } } }
from http://rkdudwydkv.tistory.com/16 by ccl(A) rewrite - 2021-10-21 03:02:16