【Swift】BGMや効果音を再生する方法

手順

 

  1. 音源ファイルのパスを生成
  2. 音源プレイヤーを生成
  3. do-catch文を記述
  4. do:既に生成したプレイヤーにパスを設定したプレイヤーを設定
  5. do:音源プレイヤー再生する
  6. 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文を使わなければならない決まりがある。