|
|
|
|
@ -9,9 +9,20 @@ import Foundation |
|
|
|
|
import AVFoundation |
|
|
|
|
|
|
|
|
|
struct SoundFile { |
|
|
|
|
|
|
|
|
|
var filename: String |
|
|
|
|
var fileExtension: String |
|
|
|
|
|
|
|
|
|
init(fullName: String) throws { |
|
|
|
|
let components = fullName.components(separatedBy: ".") |
|
|
|
|
if components.count == 2 { |
|
|
|
|
self.filename = components[0] |
|
|
|
|
self.fileExtension = components[1] |
|
|
|
|
} else { |
|
|
|
|
throw SoundPlayerError.badFileName(name: fullName) |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
var url: URL? { |
|
|
|
|
return Bundle.main.url(forResource: self.filename, withExtension: self.fileExtension) |
|
|
|
|
} |
|
|
|
|
@ -19,6 +30,7 @@ struct SoundFile { |
|
|
|
|
|
|
|
|
|
enum SoundPlayerError : Error { |
|
|
|
|
case missingResourceError(file: SoundFile) |
|
|
|
|
case badFileName(name: String) |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
class SoundPlayer { |
|
|
|
|
@ -30,9 +42,9 @@ class SoundPlayer { |
|
|
|
|
throw SoundPlayerError.missingResourceError(file: soundFile) |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
let audioSession: AVAudioSession = AVAudioSession.sharedInstance() |
|
|
|
|
try audioSession.setCategory(.playback) |
|
|
|
|
try audioSession.setActive(true) |
|
|
|
|
// let audioSession: AVAudioSession = AVAudioSession.sharedInstance() |
|
|
|
|
// try audioSession.setCategory(.playback) |
|
|
|
|
// try audioSession.setActive(true) |
|
|
|
|
|
|
|
|
|
_player = try AVAudioPlayer(contentsOf: url) |
|
|
|
|
_player?.prepareToPlay() |
|
|
|
|
@ -40,11 +52,11 @@ class SoundPlayer { |
|
|
|
|
_player?.numberOfLoops = loopCount |
|
|
|
|
_player?.volume = 1.0 |
|
|
|
|
|
|
|
|
|
do { |
|
|
|
|
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.allowBluetooth, .defaultToSpeaker]) |
|
|
|
|
} catch { |
|
|
|
|
print("audioSession error = \(error)") |
|
|
|
|
} |
|
|
|
|
// do { |
|
|
|
|
// try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.allowBluetooth, .defaultToSpeaker]) |
|
|
|
|
// } catch { |
|
|
|
|
// print("audioSession error = \(error)") |
|
|
|
|
// } |
|
|
|
|
|
|
|
|
|
_player?.play() |
|
|
|
|
|
|
|
|
|
|