AudioPlayer.swift
import AVFoundation
class AudioPlayer {
static let shared = AudioPlayer()
private init() {}
private var player = AVAudioPlayer()
func playAlarm() {
let url = Bundle.main.url(forResource: "alarm", withExtension: "wav", subdirectory: "raw")!
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
player.play()
} catch {
print(error.localizedDescription)
}
}
}
呼び出し方
test.swift
AudioPlayer.shared.playAlarm()