1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
| import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var myAudioPlayer: AVAudioPlayer!
var myButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let soundFilePath: NSString = NSBundle.mainBundle().pathForResource("test", ofType: "mp3")!
let fileURL: NSURL = NSURL(fileURLWithPath: soundFilePath)!
myAudioPlayer = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
myAudioPlayer.delegate = 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.whiteColor(), forState: .Normal)
myButton.backgroundColor = UIColor.darkGrayColor()
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) {
if myAudioPlayer.playing == true {
myAudioPlayer.pause()
sender.setTitle("▶︎", forState: .Normal)
} else {
myAudioPlayer.play()
sender.setTitle("■", forState: .Normal)
}
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
println("Music Finish")
myButton.setTitle("▶︎", forState: .Normal)
}
func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!) {
println("Error")
}
}
|