播放音效

首先在 Xcode 裡,新建一個 Single View Application 類型的專案,取名為 ExSound 。

一開始先以加入檔案的方式加入一個音效檔案,並為 ViewController 建立一個變數以供後續使用,如下:

class ViewController: UIViewController {
    var myPlayer :AVAudioPlayer!

    // 省略
}

引入函式庫

預設的應用程式沒有包含音效相關的函式,所以需先引入 AVFoundation 函式庫,如下:

import AVFoundation

建立播放器變數

viewDidLoad()中建立變數,用來控制音效相關的動作:

// 建立播放器
let soundPath = Bundle.main.path(
    forResource: "woohoo", ofType: "wav")
do {
    myPlayer = try AVAudioPlayer(
        contentsOf: URL(fileURLWithPath: soundPath!))

    // 重複播放次數 設為 0 則是只播放一次 不重複
    myPlayer.numberOfLoops = 0

} catch {
    print("error")
}

上述程式先取得音效檔案的路徑,再將音效檔案傳入初始化播放器當做參數建立。這是一個拋出函式,所以需以do-catch語句來定義錯誤的捕獲及處理

接著則是建立一個按鈕,按下時會播放音效:

// 建立一個按鈕
let myButton = UIButton(frame: CGRect(
  x: 100, y: 200, width: 100, height: 60))
myButton.setTitle("音效", for: .normal)
myButton.setTitleColor(
  UIColor.blue, for: .normal)
myButton.addTarget(
  self, 
  action: #selector(ViewController.go),
  for: .touchUpInside)
self.view.addSubview(myButton)

按下按鈕後執行動作的方法:

@objc func go() {
    // 播放音效
    myPlayer.play()
}

以上即為這個範例的內容。

音效來源

範例

本小節範例程式碼放在 apps/todo

results matching ""

    No results matching ""