Created
October 24, 2024 00:17
-
-
Save takoikatakotako/021d00fcbfdd9da079500f0b572710c8 to your computer and use it in GitHub Desktop.
SwiftUIでAVAudioPlayerで音楽を再生し、再生終了を検知する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import SwiftUI | |
| struct ContentView: View { | |
| @StateObject var viewModel = ContentViewState() | |
| var body: some View { | |
| VStack { | |
| Button("Play") { | |
| viewModel.playAudio() | |
| } | |
| } | |
| } | |
| } | |
| #Preview { | |
| ContentView() | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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