音を鳴らしたいだけ
ある教材でアプリ開発を学んでいたら、音を鳴らすところがうまくいかない。そりゃそうだ。その教材、Swift3.0なんだもの。まぁ、私が過去に書いた4.2を引っ張ってきてぶち込んだから問題なくできたけど。。。こんな感じで今後も「音を鳴らすだけ」のためにわざわざ過去のProject開いて確認するのめんどいな、、と思ってここに書いておく。
こんな感じ
ViewController.swift
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer!
@IBAction func btn(_ sender: UIButton) {
playSound(name: "yourFileName")
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension ViewController: AVAudioPlayerDelegate{
func playSound(name: String){
guard let path = Bundle.main.path(forResource: name, ofType: "mp3") else {
print("I cannot find any music file...")
return
}
do{
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
audioPlayer.delegate = self
audioPlayer.play()
} catch {
}
}
}
yourFileName.mp3っていうファイルを入れておくと、ボタンを押した時にそれが流れる。