LoginSignup
5
6

More than 5 years have passed since last update.

iOS8 音を鳴らす

Last updated at Posted at 2015-08-13

準備:mp3音源をプロジェクトに追加(プロジェクトフォルダ右区rックで追加)

1、音源へのパスを生成
2、AVAudioPlayerのインスタンス化
3、AVAudioPlayerのデリゲートを設定
4、タップしたときに音を鳴らす止めるなどの処理
5、イベント処理

:exclamation:注意点:exclamation:
xcode7betaでは「2、AVAudioPlayerのインスタンス化」で例外処理を記載しないとビルドエラーになる
 

//
//  ViewController.swift
//  sousa
//
//  Created by Misato Morino on 2015/08/13.
//  Copyright (c) 2015年 Atsushi Komuro. All rights reserved.
//

import UIKit
import AVFoundation

//AudioPlayerDelegate
class ViewController: UIViewController,AVAudioPlayerDelegate {

    //変数宣言.
    var myAudioPlayer : AVAudioPlayer! = nil
    var myButton : UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        //再生する音源のURLを生成.
        let soundFilePath : NSString = NSBundle.mainBundle().pathForResource("Sample", ofType: "mp3")!
        let fileURL : NSURL = NSURL(fileURLWithPath: soundFilePath as String)

        //AVAudioPlayerのインスタンス化
        do{
            myAudioPlayer = try AVAudioPlayer(contentsOfURL: fileURL, fileTypeHint:nil)
        }catch{
            print("Failed AVAudioPlayer Instance")
        }

        //AVAudioPlayerのデリゲートをセット.
        myAudioPlayer.delegat = self

        //ボタンの生成
        myButton = UIButton()
        myButton.frame.size = CGSizeMake(100, 100)
        myButton.layer.position = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2)
        myButton.setTitle("▶︎", forState: UIControlState.Normal)
        myButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
        myButton.backgroundColor = UIColor.cyanColor()
        myButton.addTarget(self, action: "onClickMyButton:", forControlEvents: UIControlEvents.TouchUpInside)
        myButton.layer.masksToBounds = true
        myButton.layer.cornerRadius = 50.0
        self.view.addSubview(myButton)
    }

    //ボタンがタップされた時に呼ばれるメソッド.
    func onClickMyButton(sender: UIButton) {

        //playingプロパティがtrueであれば音源再生中.
        if myAudioPlayer.playing == true {

            //myAudioPlayerを一時停止.
            myAudioPlayer.pause()
            sender.setTitle("▶︎", forState: .Normal)
        } else {

            //myAudioPlayerの再生.
            myAudioPlayer.play()
            sender.setTitle("■", forState: .Normal)
        }
    }

    //音楽再生が成功した時に呼ばれるメソッド.
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        print("Music Finish")

        //再度myButtonを"▶︎"に設定.
        myButton.setTitle("▶︎", forState: .Normal)
    }

    //デコード中にエラーが起きた時に呼ばれるメソッド.
    func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer, error: NSError?) {
        print("Error")
    }
}
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6