[UIKit] Audio Handling Snippet

  • Sử dụng AVAudioPlayer để phát nhạc
  • Xử lý lỗi khi load file âm thanh
  • Cung cấp controls để play/stop
  • Hỗ trợ loop vô hạn

Import thư viện Audio

import AVFoundation

Khai báo audio player

// Khai báo audio player
var audioPlayer: AVAudioPlayer!
var isSoundOn: Bool = false
var soundName: String = "goodnight-sound"

Khởi tạo audio player

// Khởi tạo audio player
func prepareAudioPlayer() {
    guard let url = Bundle.main.url(forResource: soundName, withExtension: "mp3")
    else {
        print("Music file is not found!")
        return
    }
    
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: url)
        audioPlayer.numberOfLoops = -1  // Lặp vô hạn
        audioPlayer.prepareToPlay()
        print("\(soundName) will be played!")
    } catch {
        print("Error initializing AVAudioPlayer: \(error.localizedDescription)")
    }
}

Toggle âm thanh

// Toggle âm thanh
@IBAction func toggleSound(_ sender: UISwitch) {
    if (isSoundOn) {
        isSoundOn = false
        audioPlayer.stop()
    } else {
        isSoundOn = true
        audioPlayer.play()
    }
    swToggleSound.isOn = isSoundOn
}