如何在Swift中播放聲音?
在Swift中,有一個名為AVFoundation的框架,它提供了播放音訊檔案的靈活性。這個框架提供了一個名為AVAudioPlayer的類來管理音訊播放和暫停。在本文中,您將學習如何在Swift中使用AVAudioPlayer類播放聲音。
AVFoundation
此框架是Swift中一個非常強大的多媒體框架。它為您提供了處理媒體檔案(如音訊、影片和其他型別的媒體檔案)的大部分功能。此框架使用一些常用類來管理媒體檔案。
AVPlayer − 此類支援高質量的音訊和影片播放。它可以播放本地或遠端媒體檔案,並具有停止、搜尋和音量調節的控制元件。
AVAudioPlayer − 這是一個AVPlayer子類,專門設計用於播放音訊檔案。它還具有其他功能,例如調整迴圈次數、修改播放速度和調整音量。
AVCaptureSession − 此類用於從輸入裝置(如攝像頭和麥克風)捕獲媒體素材。它可以錄製影片和音訊,並且可以選擇更改曝光、焦點和其他捕獲設定。
AVAsset − 此類表示媒體資產,例如影片或音訊檔案。它提供資產元資料,例如持續時間和格式,並可用於提取影片素材的單個幀或部分。
AVMetadata − 此類用於處理媒體資產元資料,例如標題、藝術家和專輯資訊。它可以讀取和寫入元資料,併為常用元資料欄位提供一組定義的鍵。
AVPlayerLayer − 一個能夠顯示AVPlayer例項中影片素材的圖層子類。它允許您將影片播放整合到程式的使用者介面中,並提供修改縱橫比和其他顯示引數的選項。
這些只是AVFoundation框架中最有價值的類和功能中的一部分。使用Swift,有多種不同的類和API可用於與媒體資產互動,包括對即時音訊處理、影片編輯等的支援。
AVAudioPlayer類是AVFoundation框架中AVPlayer類的子類,它提供了一個簡單的介面,用於在Swift應用程式中播放音訊內容。以下是AVAudioPlayer類的一些關鍵屬性和方法:
屬性
currentTime − 此屬性返回音訊檔案的當前播放時間(以秒為單位)。
duration − 此屬性返回音訊檔案的持續時間(以秒為單位)。
volume − 此屬性設定音訊播放的音量,範圍為0.0(靜音)到1.0(最大音量)。
numberOfLoops − 此屬性設定音訊檔案在停止之前應播放的次數。值為-1表示音訊檔案應無限迴圈。
isPlaying − 此屬性返回一個布林值,指示音訊檔案當前是否正在播放。
方法
init(contentsOf url: URL) − 這是AVAudioPlayer類的指定初始化器,它接受要播放的音訊檔案的URL。
play() − 此方法啟動音訊檔案的播放。
pause() − 此方法暫停音訊檔案的播放。
stop() − 此方法停止音訊檔案的播放。
prepareToPlay() − 此方法準備音訊播放器進行播放,方法是將音訊檔案載入到記憶體中並執行任何必要的初始化。
setVolume(_ volume: Float, fadeDuration: TimeInterval) − 此方法設定音訊播放器的音量,並可以選擇淡入或淡出持續時間。
currentTime (setter) − 此方法設定音訊檔案的當前播放時間(以秒為單位)。
numberOfLoops (setter) − 此方法設定音訊檔案在停止之前應播放的次數。
以下是如何播放和暫停聲音的示例
步驟1 − 首先,將音訊檔案新增到您的專案目錄。在此示例中,我們將名為“sample_audio.mp3”的音訊檔案新增到本地目錄。
步驟2 − 為了在Swift中播放音訊檔案,您需要匯入AVFoundation框架。
步驟3 − 現在,我們宣告一個屬性,例如“var audioPlayer: AVAudioPlayer?”來播放音訊檔案。
步驟4 − 您可以初始化AVAudioPlayer類的物件。您可以透過提供音訊檔案的本地URL來使用AVAudioPlayer(contentsOf: URL)初始化器。
步驟5 − 要從URL播放和暫停音訊檔案,您需要呼叫“play”和“pause”方法來暫停正在進行的音訊檔案。
示例
import UIKit import AVFoundation class TestController: UIViewController { private var audioPlayer: AVAudioPlayer? private lazy var playButton: UIButton = { let button = UIButton() button.backgroundColor = .darkGray button.setTitle("Play Sound", for: .normal) button.setTitleColor(.white, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .medium) button.layer.cornerRadius = 10 button.clipsToBounds = true button.addTarget(self, action: #selector(handleButtonTapped), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() override func viewDidLoad() { super.viewDidLoad() initialSetup() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } private func initialSetup() { view.backgroundColor = .white navigationItem.title = "Play Sound" view.addSubview(playButton) playButton.heightAnchor.constraint(equalToConstant: 45).isActive = true playButton.widthAnchor.constraint(equalToConstant: 250).isActive = true playButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true playButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } @objc private func handleButtonTapped() { if audioPlayer != nil && audioPlayer!.isPlaying { audioPlayer?.pause() playButton.setTitle("Play Sound", for: .normal) } else { guard let path = Bundle.main.path(forResource: "sample_audio", ofType:"mp3") else { return } let url = URL(fileURLWithPath: path) do { if audioPlayer == nil { audioPlayer = try AVAudioPlayer(contentsOf: url) } audioPlayer?.play() playButton.setTitle("Pause Sound", for: .normal) } catch let error { print(error.localizedDescription) } } } }
輸出
結論
您可以匯入AVFoundation框架來使用AVAudioPlayer類。此類為您提供了播放和暫停音訊檔案的功能。此類還提供其他屬性和方法來管理執行。