【AVFoundation】初心者だけどwav効果音を鳴らしてみた!【swift】

AVFoundationで効果音を鳴らしてみた.

スポンサードリンク



何をしたのか

sound.wavというファイルを鳴らしたい. 今回はviewDidLoad(Viewが呼ばれたときに動くところ)の中に音を鳴らすように書いたので, アプリを起動したら音が鳴るようになってます.

準備するもの

sound.wav(音ファイル)
このふぁいるをこんな感じで置いておく
f:id:sekibotbot:20160302145125p:plain

気をつける点

  1. AVFoundationをimportする
  2. do-try-catchを使う. これを使わないとエラーでました.

code

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer: AVAudioPlayer?
    
//音を鳴らすための関数
    func playsound(){
        if let path = NSBundle.mainBundle().pathForResource("can-open1", ofType: "wav") {
            do{
                audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path), fileTypeHint: "wav")
            }catch{
            }
            
            if let sound = audioPlayer {
                sound.prepareToPlay()
                sound.play()
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    playsound()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

これでおっけー