【Swift】BGMや効果音を再生する方法
手順
- 音源ファイルのパスを生成
- 音源プレイヤーを生成
- do-catch文を記述
- do:既に生成したプレイヤーにパスを設定したプレイヤーを設定
- do:音源プレイヤー再生する
- catch:エラーが起こった場合の処理
ソースコード
//パス let notificationPath = Bundle.main.path(forResource: "通知オン", ofType: "mp3") //プレイヤー var notificationPlayer = AVAudioPlayer() do { //パスを設定したプレイヤーを設定 notificationPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: notificationPath!)) //音楽プレイヤーを再生 notificationPlayer.play() } catch { //エラーが起きた時の処理 print("通知音でエラー発生") }
注意点
音楽プレイヤーを使用する場合、必ずdo-catch文を使わなければならない決まりがある。