当アカウントへ訪れていただき、誠にありがとうございます。第20回アプリ教室では、音楽再生アプリを作ります。自分のペースで勉強したい、勉強前に予習したい、内容を復習したい場合、ご利用ください。
Meetup
http://www.meetup.com/ios-dev-in-namba/
http://learning-ios-dev.esy.es/
株式会社ジーライブ http://geelive-inc.com
0-2. 音楽ファイルをダウンロード
1-1. main.storyboardを選択し、UI部品から下記を配置します。(ドラッグ&ドロップ)
1-2. Storyboardの下記UI部品を、ViewController.swiftに紐づけます(control押しながらドラッグ)
- UIButton 再生ボタン (actionで紐付ける)
- UIButton 停止ボタン (actionで紐付ける)
- 以下コードブロックを記入
import UIKit
import AVFoundation // オーディオプレイヤー使うとき、インポートしましょう
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
initAudioPlayer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// audioPlayer初期化
func initAudioPlayer()
{
let filePath = Bundle.main.path(forResource: "sound", ofType: "mp3")
let audioPath = URL(fileURLWithPath: filePath!)
audioPlayer = try? AVAudioPlayer(contentsOf: audioPath)
audioPlayer?.prepareToPlay()
}
@IBAction func play(_ sender: UIButton) {
audioPlayer?.play()
}
@IBAction func stop(_ sender: UIButton) {
audioPlayer?.stop()
}
}