1 import UIKit
2 import AVFoundation
3
4 class ViewController:UIViewController,
AVAudioPlayerDelegate {
5 var audioPlayer:AVAudioPlayer = AVAudioPlayer()
6 override func viewDidLoad() {
7 super.viewDidLoad()
8 // Do any additional setup after loading the view,
typically from a nib.
9 let path = Bundle.main.path(forResource:“music”,
ofType:“mp3”)
10 let soundUrl = URL(fileURLWithPath:path!)
11
12 do{
13 try audioPlayer = AVAudioPlayer(contentsOf:
soundUrl)
14 audioPlayer.volume = 1.0
15 audioPlayer.numberOfLoops = -1
16 audioPlayer.delegate = self
17 audioPlayer.play()
18 } catch{
19 print(error)
20 }
21 let stopMusic = UIButton(frame:CGRect(x:20, y:
80, width:280, height:44))
22 stopMusic.backgroundColor = UIColor.purple
23 stopMusic.setTitle(“暂停/恢复音乐”, for:
UIControlState.init(rawValue:0))
24 stopMusic.addTarget(self, action:
selector(ViewController.pauseOrResumeMusic),
for:.touchUpInside)
25 self.view.addSubview(stopMusic)
26 }
27 func pauseOrResumeMusic(){
28 if self.audioPlayer.isPlaying {
29 self.audioPlayer.pause()
30 }
31 else{
32 self.audioPlayer.play()
33 }
34 }
35 func audioPlayerBeginInterruption(_ player:
AVAudioPlayer) {
36 print(“音乐播放被打断。”)
37 }
38 func audioPlayerDidFinishPlaying(_ player:
AVAudioPlayer, successfully flag:Bool) {
39 print(“音乐播放完毕。”);
40 }
41 }