[swift超入門] ボタンを押すことで効果音を流す
Xcode上での画面作成にあたって
用いたフレームワーク
1.UIKit(ファイル作成時に自動で導入されています)
2.AVFoundation(効果音を流すために使います)
用いたオブジェクト
1.imageview(Assets.xcassetsでのナビゲータエリアで追加したimageに猫の画像を導入)
2.button(ビューコントローラに接続)
その他注意点
画像ファイルをsound.swiftファイルの中に保存しています。
今回用いたコード
コードは、[Swift3]ボタンを押した時に効果音を鳴らすを参考にさせていただきました。
sound.swift
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayerInstance : AVAudioPlayer! = nil // 再生するサウンドのインスタンス
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// サウンドファイルのパスを生成(今回のファイルに導入した画像ファイル名を書きます)
let soundFilePath = Bundle.main.path(forResource: "meow", ofType: "mp3")!
let sound:URL = URL(fileURLWithPath: soundFilePath)
// AVAudioPlayerのインスタンスを作成,ファイルの読み込み
do {
audioPlayerInstance = try AVAudioPlayer(contentsOf: sound, fileTypeHint:nil)
} catch {
print("AVAudioPlayerインスタンス作成でエラー")
}
// 再生準備
audioPlayerInstance.prepareToPlay()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func sound(_ sender: UIButton) {
// 連打した時に連続して音がなるようにする
audioPlayerInstance.currentTime = 0 // 再生箇所を頭に移す
audioPlayerInstance.play() // 再生する
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
実機画面
最後に
自分にとって初めての投稿となりました。ご意見、ご指摘の方お気軽によろしくお願いいたします。