Skip to content

Instantly share code, notes, and snippets.

@takoikatakotako
Created October 24, 2024 00:17
Show Gist options
  • Select an option

  • Save takoikatakotako/021d00fcbfdd9da079500f0b572710c8 to your computer and use it in GitHub Desktop.

Select an option

Save takoikatakotako/021d00fcbfdd9da079500f0b572710c8 to your computer and use it in GitHub Desktop.
SwiftUIでAVAudioPlayerで音楽を再生し、再生終了を検知する
import SwiftUI
struct ContentView: View {
@StateObject var viewModel = ContentViewState()
var body: some View {
VStack {
Button("Play") {
viewModel.playAudio()
}
}
}
}
#Preview {
ContentView()
}
import SwiftUI
import AVFoundation
class ContentViewState: NSObject, ObservableObject {
var audioPlayer: AVAudioPlayer?
func playAudio() {
guard let url = Bundle.main.url(forResource: "melody", withExtension: "mp3") else { return }
audioPlayer = try? AVAudioPlayer(contentsOf: url)
audioPlayer?.delegate = self
audioPlayer?.play()
}
}
extension ContentViewState: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print("Did finish Playing")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment