폰으로 음악을 자주 듣지않고있기에 간단히 만든 앱을 사용하여 가끔 음악을 듣는다
유튜브영상을 URL을 입력하면 mp3파일로 만들어 다운로드하게 해주는 사이트에서 파일을 받아 재생하는 용도이다
솔직히 이러면 그냥 기본 파일앱에 연동되어있는걸로 재생하는게 편한데 어쩌다 3편글까지 왔는지 기억이 가물가물...
아마 공부를 겸해서 그런거겠거늘한다
아무튼 기본앱에는 있는 기능은 잠금화면에서의 컨트롤바가 내 앱에는 없다
그래서 이번엔 이걸 추가하려고하였으나....
며칠 고생했으나 문제를 찾지 못했고 그렇게 그냥 묵혀두다 오늘 다시 시작했다
아마 설정문제이겠거늘 싶긴한데 예제로 구한 앱과 다른 설정부분을 찾지 못했고 나는 이참에 아예 소스를 다 들어내고 처음부터 배치를 다시할까 한다
우선 관련된 클래스는
MPRemoteCommandCenter
https://developer.apple.com/documentation/mediaplayer/mpremotecommandcenter
MPRemoteCommandCenter | Apple Developer Documentation
An object that responds to remote control events sent by external accessories and system controls.
developer.apple.com
그래고 메서드는
beginReceivingRemoteControlEvents()
beginReceivingRemoteControlEvents() | Apple Developer Documentation
Tells the app to begin receiving remote-control events.
developer.apple.com
추가로
공식예제는 아래의 링크이다.
https://developer.apple.com/documentation/mediaplayer/becoming_a_now_playable_app
Becoming a now playable app | Apple Developer Documentation
Ensure your app is eligible to become the Now Playing app by adopting best practices for providing Now Playing info and registering for remote command center actions.
developer.apple.com
그런데 솔직히 공식 예제는 분리가 너무 많이 되어있어서 읽기 귀찮다
뭐 아무튼 그래서 우선 모든 코드들을 동작하지 않게 처리하고
아래와 같은 순서로 앱의 리빌드할꺼다
1. 백그라운드 오디오 재생에 필요한 권한 처리 info.plist
2. 플레이어 생성 -> 기존 avplyaer에서 avQueuePlayer로 대체
3. MPRemoteCommandCenter 설정 및 설정
4. ui코드 재위치
5. 각 이벤트 연결 및 테스트
- 계획만 짜두고 한동안 잡지않다가 다시 시작
기존 코드들을 죄다 old폴더에 넣고 새로운 vc에서 통합하여 사용하여 문제되는 라인을 찾았다
전부 다 통합하여 재 구축해도 되지않아서 당황하다가 얼떨결에 찾은거라 이유를 모르겠다 누가좀 알려줬으면 좋겠네
문제되는 라인은 바로
// try audioSession.setCategory(.playback, mode: .default, options: [.mixWithOthers])
try audioSession.setCategory(.playback, mode: .default, options: [])
카테고리 설정하는 부분
타 앱 소리가 나도 같이 들리도록 옵션을 추가해줬었는데
이 설정을 하다가 깜빡 옵션을 안넣어줬었는데 락스크린에 컨트롤바가 생겼다.
너무 어처구니없는 상황에 웃음만 나온다
일단 이 포스트가 아마도 락스크린의 컨트롤바를 설정하는거라 해당 부분 소스를 올리자면
func remoteCommandCenterSetting() {
// remote control event 받기 시작
UIApplication.shared.beginReceivingRemoteControlEvents()
let center = MPRemoteCommandCenter.shared()
center.playCommand.removeTarget(nil)
center.pauseCommand.removeTarget(nil)
// 제어 센터 재생버튼 누르면 발생할 이벤트를 정의합니다.
center.playCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in
self.avPlayer.play()
MPNowPlayingInfoCenter.default()
.nowPlayingInfo?[MPNowPlayingInfoPropertyElapsedPlaybackTime] = NSNumber(value: self.avPlayer.currentTime)
// 재생 할 땐 now playing item의 rate를 1로 설정하여 시간이 흐르도록 합니다.
MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyPlaybackRate] = 1
return .success
}
// 제어 센터 pause 버튼 누르면 발생할 이벤트를 정의합니다.
center.pauseCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in
self.avPlayer.pause()
MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyElapsedPlaybackTime] = NSNumber(value: self.avPlayer.currentTime)
// 일시정지 할 땐 now playing item의 rate를 0으로 설정하여 시간이 흐르지 않도록 합니다.
MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPNowPlayingInfoPropertyPlaybackRate] = 0
return .success
}
center.nextTrackCommand.addTarget { event in
let nextResult = self.nextAction()
if !nextResult {
return .noSuchContent
}
return .success
}
center.previousTrackCommand.addTarget { event in
_ = self.previousAction()
return .success
}
center.playCommand.isEnabled = true
center.pauseCommand.isEnabled = true
}
func remoteCommandInfoCenterSetting() {
let center = MPNowPlayingInfoCenter.default()
var nowPlayingInfo = center.nowPlayingInfo ?? [String: Any]()
guard let currentMusic: MusicInfo = playList.currentMusic else {
print("리스트에 곡이 없음")
return
}
nowPlayingInfo[MPMediaItemPropertyTitle] = currentMusic.title
nowPlayingInfo[MPMediaItemPropertyArtist] = currentMusic.artist
if let albumCoverPage = currentMusic.artworkImage {
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: albumCoverPage.size, requestHandler: { size in
return albumCoverPage
})
}
// 콘텐츠 총 길이
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = self.avPlayer.duration
// 콘텐츠 재생 시간에 따른 progressBar 초기화
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = 1
// 콘텐츠 현재 재생시간
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = NSNumber(value: self.avPlayer.currentTime)
center.nowPlayingInfo = nowPlayingInfo
}
이곳저곳에서 퍼오면서 테스트하고 기우고 이래서 출처가 기억이 안남.
전체 소스는 내 깃에 있다.
https://github.com/wiwi-git/proj_ypl
GitHub - wiwi-git/proj_ypl: ios에서 간단하게 쓸 백그라운드 플레이어가 필요하다
ios에서 간단하게 쓸 백그라운드 플레이어가 필요하다. Contribute to wiwi-git/proj_ypl development by creating an account on GitHub.
github.com
todo로 잡아뒀던 기능들이 몇개 있는데 이건 그냥 포기하고 이후에 다시 글을 쓰게된다면 통합시켜놨던걸 mvvm으로 분리시키고
uikit으로 작성된 ui를 swiftui로 변경해볼까 한다
swiftui는 그냥 몇번 훑어보고 말아서 이참에 공부해야지
'iOS > swift' 카테고리의 다른 글
[ios 키보드 프로젝트] 1. 키보드 프로젝트를 끝내자. (0) | 2025.01.17 |
---|---|
background audio play - 4 [mvvm 패턴] (1) | 2024.11.27 |
background audio play - 2 [AVAudioSession] (1) | 2024.09.15 |
background audio play - 1 [AVAudioPlayer] (2) | 2024.09.12 |
앱이 열리면 뱃지 카운트 0으로 설정하기 (0) | 2024.04.28 |