Created
September 2, 2019 15:00
-
-
Save PaulWoodIII/593d3023028cbc8d2e094aa05dfd1949 to your computer and use it in GitHub Desktop.
Some gameplay sounds written in swift using Combine, I'm acting like this is a legacy component even though it isn't so it uses NSNotificationCenter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Sounds.swift | |
// | |
// Created by Paul Wood on 9/2/19. | |
// Copyright © 2019 Paul Wood. All rights reserved. | |
// | |
import Foundation | |
import Combine | |
import AVFoundation | |
import MinesweeperGameplay | |
class Sounds: NSObject { | |
var cancelBag: Set<AnyCancellable> = [] | |
struct NameFunction { | |
let name: Notification.Name | |
let function: Selector | |
} | |
let sinkMappings: [NameFunction] = { | |
return [ | |
NameFunction(name: Notification.Name.click, function: #selector(didClickEmpty)), | |
NameFunction(name: Notification.Name.flagOn, function: #selector(didFlagOn)), | |
NameFunction(name: Notification.Name.flagOff, function: #selector(didFlagOff)), | |
] | |
}() | |
override init() { | |
super.init() | |
sinkMappings.forEach { (mapping: Sounds.NameFunction) in | |
self.cancelBag.insert( | |
NotificationCenter.default.publisher(for: mapping.name).sink(receiveValue: { _ in | |
self.perform(mapping.function) | |
}) | |
) | |
} | |
} | |
var player: AVAudioPlayer? | |
@objc func didClickEmpty() { | |
playSound("click") | |
} | |
@objc func didFlagOn() { | |
playSound("flag") | |
} | |
@objc func didFlagOff() { | |
playSound("flag") | |
} | |
@objc func didWin() { | |
//TODO | |
} | |
@objc func didLose() { | |
//TODO | |
} | |
func playSound(_ name: String = "click") { | |
guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return } | |
do { | |
try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default) | |
try AVAudioSession.sharedInstance().setActive(true) | |
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/ | |
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue) | |
guard let player = player else { return } | |
player.play() | |
} catch let error { | |
print(error.localizedDescription) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment