[Swift通天遁地]八、媒體與動畫-(1)實現音頻的播放和停止
阿新 • • 發佈:2019-02-06
demo 開始 works handle 根據 normal int orm 控件
本文將演示實現對音頻播放的控制。
首先確保在項目中,已經安裝了所需的第三方類庫,點擊查看安裝的配置文件。
1 platform :ios, ‘8.0‘ 2 use_frameworks! 3 4 target ‘DemoApp‘ do 5 source ‘https://github.com/CocoaPods/Specs.git‘ 6 pod ‘CryptoSwift‘, :git => "https://github.com/krzyzanowskim/CryptoSwift", :branch => "master" 7 end
根據配置文件中的相關設置,安裝第三方類庫。
完成安裝之後,雙擊打開項目文件【DemoApp.xcworkspace】
往項目中導入了一個音頻文件。
在左側的項目導航區,打開視圖控制器的代碼文件【ViewController.swift】
1 import UIKit 2 //在當前的類文件中,引入已經安裝的第三方類庫。 3 import AudioPlayer 4 5 class ViewController: UIViewController { 6 //添加一個音頻播放器,作為當前類的一個屬性。 7 var audioPlayer:AudioPlayer! 8 overridefunc viewDidLoad() { 9 super.viewDidLoad() 10 // Do any additional setup after loading the view, typically from a nib. 11 // Initialize 12 13 //添加一個按鈕,當用戶點擊該按鈕時,開始播放該文件。 14 let play = UIButton(frame: CGRect(x: 40, y: 80, width: 240, height: 40)) 15 //設置按鈕在正常狀態下的標題文字 16 play.setTitle("Play", for: .normal) 17 //設置按鈕的背景顏色為橙色 18 play.backgroundColor = UIColor.orange 19 //給播放按鈕控件綁定點擊事件 20 play.addTarget(self, action: #selector(ViewController.playMusic(_:)), for: UIControl.Event.touchUpInside) 21 22 //添加第二個按鈕,當用戶點擊該按鈕時,停止音頻文件的播放 23 let stop = UIButton(frame: CGRect(x: 40, y: 180, width: 240, height: 40)) 24 //設置按鈕在正常狀態下的標題文字 25 stop.setTitle("Stop", for: .normal) 26 //設置按鈕的背景顏色為橙色 27 stop.backgroundColor = UIColor.orange 28 //給停止按鈕控件綁定點擊事件 29 stop.addTarget(self, action: #selector(ViewController.stopMusic(_:)), for: UIControl.Event.touchUpInside) 30 31 //設置根視圖的背景顏色 32 self.view.backgroundColor = UIColor.orange 33 //將兩個按鈕依次添加到根視圖 34 self.view.addSubview(play) 35 self.view.addSubview(stop) 36 37 //添加一個異常捕捉語句,用來初始化音頻播放對象 38 do 39 { 40 //讀取項目中的音頻文件,並初始化一個音頻播放器 41 try audioPlayer = AudioPlayer(fileName: "music.mp3") 42 43 //給音頻播放器添加一個播放結束事件監聽器, 44 audioPlayer.completionHandler = {(_ didFinish: Bool) -> Void in 45 //當播放結束時,在控制臺輸出提示語句。 46 print("---The music finishes playing, or is stopped.") 47 } 48 } 49 catch 50 { 51 print("---Sound initialization failed") 52 } 53 } 54 55 //添加一個方法,用來響應播放按鈕的點擊事件 56 @objc func playMusic(_ button:UIButton) 57 { 58 //設置音頻播放器音量的大小,範圍從0.0到1.0 59 audioPlayer.volume = 0.8 60 //設置音頻播放的循環次數為3 61 audioPlayer.numberOfLoops = 3 62 //調用音頻播放器的播放方法,開始播放指定的音頻文件。 63 audioPlayer.play() 64 } 65 66 //添加一個方法,用來響應停止按鈕的點擊事件 67 @objc func stopMusic(_ button:UIButton) 68 { 69 //當音頻播放器處於播放狀態時 70 if audioPlayer.isPlaying 71 { 72 //在控制臺輸出播放的時長 73 print(audioPlayer.duration) 74 //輸出播放器當前的時刻 75 print(audioPlayer.currentTime) 76 //在控制臺輸出音頻文件的名稱 77 print(audioPlayer.name ?? "") 78 //以及音頻文件在項目中的路徑 79 print(audioPlayer.url ?? "") 80 81 //調用播放器的淡出方法,在1秒鐘內,逐漸停止音頻的播放 82 audioPlayer.fadeOut(duration: 1.0) 83 84 //或者立即停止音樂的播放, 85 //直接調用音頻播放器的停止方法。 86 audioPlayer.stop() 87 } 88 } 89 90 override func didReceiveMemoryWarning() { 91 super.didReceiveMemoryWarning() 92 // Dispose of any resources that can be recreated. 93 } 94 }
[Swift通天遁地]八、媒體與動畫-(1)實現音頻的播放和停止