【AVFoundation】初心者だけどwav効果音を鳴らしてみた!【swift】
AVFoundationで効果音を鳴らしてみた.
スポンサードリンク
何をしたのか
sound.wavというファイルを鳴らしたい. 今回はviewDidLoad(Viewが呼ばれたときに動くところ)の中に音を鳴らすように書いたので, アプリを起動したら音が鳴るようになってます.
準備するもの
sound.wav(音ファイル)
このふぁいるをこんな感じで置いておく
気をつける点
- AVFoundationをimportする
- do-try-catchを使う. これを使わないとエラーでました.
初心者がとったいろんな対策などはこちら
【cocoaPods】初心者だけどbut they required a higher minimum deployment target.って言われた件 - sekibotbotのブログ
swift カテゴリーの記事一覧 - sekibotbotのブログ
iphoneアプリ カテゴリーの記事一覧 - sekibotbotのブログ
↑スポンサードリンク
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. } }
これでおっけー