├── .gitignore ├── GameSoundEngine.podspec ├── LICENSE ├── README.md └── SoundEngine ├── SoundEngine.xcodeproj ├── project.pbxproj └── project.xcworkspace │ └── contents.xcworkspacedata └── SoundEngine ├── Info.plist ├── Int+Extensions.swift ├── SoundEngine.h ├── SoundEngine.swift └── SoundSFX.swift /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xcuserstate 23 | 24 | ## Obj-C/Swift specific 25 | *.hmap 26 | *.ipa 27 | *.dSYM.zip 28 | *.dSYM 29 | 30 | ## Playgrounds 31 | timeline.xctimeline 32 | playground.xcworkspace 33 | 34 | # Swift Package Manager 35 | # 36 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 37 | # Packages/ 38 | .build/ 39 | 40 | # CocoaPods 41 | # 42 | # We recommend against adding the Pods directory to your .gitignore. However 43 | # you should judge for yourself, the pros and cons are mentioned at: 44 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 45 | # 46 | # Pods/ 47 | 48 | # Carthage 49 | # 50 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 51 | # Carthage/Checkouts 52 | 53 | Carthage/Build 54 | 55 | # fastlane 56 | # 57 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 58 | # screenshots whenever they are needed. 59 | # For more information about the recommended setup visit: 60 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md 61 | 62 | fastlane/report.xml 63 | fastlane/Preview.html 64 | fastlane/screenshots 65 | fastlane/test_output 66 | -------------------------------------------------------------------------------- /GameSoundEngine.podspec: -------------------------------------------------------------------------------- 1 | # 2 | 3 | Pod::Spec.new do |s| 4 | 5 | # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 6 | # 7 | 8 | s.name = "GameSoundEngine" 9 | s.version = "1.2" 10 | s.summary = "A simple, easy to use sound engine written in Swift, designed for iOS games." 11 | 12 | s.description = "GameSoundEngine supports playing background music and multiple simultaneous sound effects. To help ensure sonic variety, sound effects can be played with random pitch and volume levels, as well as randomly from a group of sound effects." 13 | 14 | s.homepage = "https://github.com/tkier/GameSoundEngine" 15 | 16 | 17 | # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 18 | # 19 | 20 | s.license = "Apache License, Version 2.0" 21 | 22 | 23 | # ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 24 | # 25 | 26 | s.author = { "Tom Kier" => "tom@endlesswavesoftware.com" } 27 | 28 | # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 29 | # 30 | 31 | s.platform = :ios, "9.0" 32 | 33 | 34 | 35 | # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 36 | # 37 | 38 | s.source = { :git => "https://github.com/tkier/GameSoundEngine.git", :tag => "#{s.version}" } 39 | 40 | # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # 41 | # 42 | 43 | s.source_files = "SoundEngine/SoundEngine/*.{h,swift}" 44 | 45 | end 46 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GameSoundEngine 2 | 3 | ## About 4 | A simple, easy to use sound engine written in Swift, designed for iOS games. It supports playing background music and multiple simultaneous sound effects. To help ensure sonic variety, sound effects can be played with random pitch and volume levels, as well as randomly from a group of sound effects. 5 | 6 | ## Installation 7 | The GameSoundEngine framework can be installed using CocoaPods. Add the following line to your project pod file and the run "pod install". 8 | 9 | ```text 10 | pod 'GameSoundEngine', '~> 1.2' 11 | ``` 12 | 13 | ## Using GameSoundEngine 14 | 15 | #### Importing the framework 16 | All Swift source files that reference the GameSoundEngine framework will need the following import statement: 17 | 18 | ```swift 19 | import GameSoundEngine 20 | ``` 21 | 22 | #### Sound Engine Initialization 23 | The Sound Engine needs to be initialized once per app session so that it can configure and setup its background music player and sound effect players. This should be done in your App Delegate didFinishLaunchingWithOptions method before any UI is displayed: 24 | 25 | ```swift 26 | SoundEngine.shared.startEngine() 27 | ``` 28 | 29 | or 30 | 31 | ```swift 32 | SoundEngine.shared.startEngine(numSFXPlayers: 20) 33 | ``` 34 | 35 | The optional numSFXPlayers parameter allows you to specify the number of sound effect players configured by the sound engine. The default value is 20 which should be sufficient for most games. But if your game needs to play large numbers of sounds simultaneously you may need to increase this number. The sound engine will let you know if numSFXPlayers needs to be increased by displaying the following message in the console: 36 | 37 | ```text 38 | All sfx players are busy. Increase numSFXPlayers in startEngine call 39 | ``` 40 | 41 | In addition to configuring sound and music players, the startEngine call also configures your app's audio session using AVAudioSession. It also creates notification listeners so that it can pause and resume sounds as needed when events such as a phone call, or Siri occur. The audio session is configured to have the following behavior as recommended by Apple's audio guidelines for game apps: 42 | 43 | - Silenced by the Ring/Silent switch and by screen locking 44 | - Pauses all audio when an audio interruption (e.g. phone call, Siri, etc.) occurs 45 | - Resumes audio when the audio interruption has ended 46 | - Play sound effects while allowing another app’s audio (i.e. the Music app) to play. 47 | - Play background music when other audio is not playing, otherwise allow the previous audio to play. 48 | 49 | #### Setting Overall Volume 50 | The master volume for background music and the master volume for all sound effects are controlled through two properties on SoundEngine object: 51 | 52 | ```swift 53 | SoundEngine.shared.backgroundMusicVolume = 1.0 54 | SoundEngine.shared.sfxVolume = 1.0 55 | ``` 56 | 57 | Valid values for the volume properties are 0.0 - 1.0, with 0.0 being no volume and 1.0 full volume. 58 | 59 | #### Background Music 60 | Background music can be played by calling the playBackgroundMusic method on the SoundEngine object: 61 | 62 | ```swift 63 | SoundEngine.shared.playBackgroundMusic("backgroundMusic.m4a", loop: true) 64 | ``` 65 | 66 | The loop parameter is optional and defaults to true when not present. 67 | 68 | To stop the background music call stopBackgroundMusic: 69 | 70 | ```swift 71 | SoundEngine.shared.stopBackgroundMusic(fadeOut: true) 72 | ``` 73 | 74 | The fadeOut parameter is optional and defaults to true. 75 | 76 | Note that only one background music file can be played at a time. Calling playBackgroundMusic while background music is already playing will stop the current music before starting the new background music. 77 | 78 | GameSoundEngine can also play a random selection from an array of background music files. 79 | 80 | ```swift 81 | SoundEngine.shared.playRandomBackgroundMusic(["music1.m4a", "music2.m4a", "music3.m4a"], loop: true) 82 | ``` 83 | 84 | If the loop parameter is set to true, each loop will play a different random selection from the array of music files. 85 | 86 | #### Sound Effects 87 | To play a sound effect you first need to create an instance of the SoundSFX class specifying the name of the sound file resource in the initializer: 88 | 89 | ```swift 90 | let fireworkSound = SoundSFX("fireworkA.caf") 91 | ``` 92 | 93 | When the SoundSFX object is created, its initializer will preload the sound data from the resource file and load it into a data buffer so it is ready to play (the preloading is done on a background thread). The buffer will be released when the SoundSFX object goes out of scope and is released. This ensures low latency when playing the sound as the data is already loaded into memory before it is played. The best practice is to create your SoundSFX objects when your scene or view is initialized and then release the objects when the scene is released and the sounds are no longer needed. 94 | 95 | To play a SoundSFX, simply call the play method on SoundSFX object: 96 | 97 | ```swift 98 | fireworkSound.play() 99 | ``` 100 | 101 | The volume for each SoundSFX can be set using an optional parameter in the initializer. The default value is 1.0. 102 | 103 | ```swift 104 | let fireworkSound = SoundSFX("fireworkA.caf", volume: 1.0) 105 | ``` 106 | 107 | #### Sound Effect Sonic Variety 108 | Sound effects that are repeated over and over during a game can become very repetitive to users. To help solve this problem SoundSFX objects can be configured to allow the sound engine to randomly set a different volume and pitch for the SoundSFX each time it is played. This will help prevent the sounds from becoming too repetitive. The amount the volume and pitch can randomly vary is controlled through optional parameters in the SoundSFX initializer: 109 | 110 | ```swift 111 | let fireworkSound = SoundSFX("fireworkA.caf", volume: 1.0, volumeVary: 2.0, pitchVary: 100.0) 112 | ``` 113 | 114 | The volumeVary value is specified in dbs. A value of 2.0 indicates that the volume can randomly vary +/- 2 dbs from the base volume specified in the volume parameter. The pitchVary is specified in cents (1 musical semitone = 100 cents, 1 octave = 1200 cents). A value of 100.0 indicates that the pitch can very +/- 100 cents. 115 | 116 | The framework contains some predefined constants that contain recommended values for the volumeVary and pitchVary values. These are good starting points, but any value can be specified. 117 | 118 | ```swift 119 | public let kVolumeVaryLow: Float = 1 // 1 db 120 | public let kVolumeVaryMedium: Float = 2 // 2 db 121 | public let kVolumeVaryLarge: Float = 3 // 3 db 122 | 123 | public let kPitchVaryLow: Float = 100 // 1 semitone 124 | public let kPitchVaryMedium: Float = 200 // 2 semitone 125 | public let kPitchVaryLarge: Float = 300 // 3 semitone 126 | ``` 127 | 128 | GameSoundEngine also supports randomly playing different variations of the same sound affect for even more sonic variety. For example if I have 3 different variations of the firework sound I can have the sound engine randomly pick one of the three different variations each time the effect is played. To accomplish this create an instance the RandomSoundSFX class and specify an array of SoundSFX objects: 129 | 130 | ```swift 131 | let fireworkSound = RandomSoundSFX([ 132 | SoundSFX("fireworkA.caf", volume: 1.0, volumeVary: kVolumeVaryLarge, pitchVary:kPitchVaryLow), 133 | SoundSFX("fireworkB.caf", volume: 1.0, volumeVary: kVolumeVaryLarge, pitchVary:kPitchVaryLow), 134 | SoundSFX("fireworkC.caf", volume: 0.3, volumeVary: kVolumeVaryLarge, pitchVary:kPitchVaryLarge) 135 | ]) 136 | ``` 137 | 138 | Now every time `fireworkSound.play()` is called the sound engine will randomly play either fireworkA.caf, fireworkB.caf, or fireworkC.caf. Note that the volume and pitch are also randomly varied as specified in the SoundSFX vary parameters. The overall effect creates a lot of sonic variety. 139 | 140 | #### Playing Sound Effects as SpriteKit Actions 141 | The framework also includes an extension to SpriteKit SKAction to allow playing SoundSFX objects as an SKAction. This makes it easier to synchronization the SoundSFX with animations in SKAction sequences and groups. 142 | 143 | ```swift 144 | let fireWorkSoundAction = SKAction.playSoundSFX(fireworkSound) 145 | ``` 146 | 147 | The parameter for the playSoundSFX method can be either a SoundSFX or a RandomSoundSFX object. Whenever the action is run, the sound effect will play. 148 | 149 | #### Sound File Formats 150 | Because the GameSoundEngine framework uses AVAudioEngine it can support any file format supported by Core Audio. However the following formats are generally recognized as good formats for iOS games due to their efficient decoding, low CPU impact and good sound quality: 151 | 152 | For background music: MPEG 4 Audio format, AAC. To convert a file to this format use the `afconvert` console command: 153 | 154 | ```text 155 | afconvert -f m4af -d aac input_file 156 | ``` 157 | 158 | For sound effects: CAF format, linear PCM, little-endian, 16-bit. To convert a file to this format use the `afconvert` console command: 159 | 160 | ```text 161 | afconvert -f caff -d LEI16 input_file 162 | ``` 163 | 164 | For best performance use the same file format for all sound effects. Playing sounds with different file formats will require GameSoundEngine to dynamically reconfigure its playback nodes to match the different file format. If all files are the same format, no reconfiguration of the playback nodes is necessary giving better performance. 165 | 166 | ## License 167 | Copyright 2016 Endless Wave Software LLC 168 | 169 | Licensed under the Apache License, Version 2.0 (the "License"); 170 | you may not use this file except in compliance with the License. 171 | You may obtain a copy of the License at 172 | 173 | http://www.apache.org/licenses/LICENSE-2.0 174 | 175 | Unless required by applicable law or agreed to in writing, software 176 | distributed under the License is distributed on an "AS IS" BASIS, 177 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 178 | See the License for the specific language governing permissions and 179 | limitations under the License. 180 | 181 | -------------------------------------------------------------------------------- /SoundEngine/SoundEngine.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | E242B7171E0E566B0047B33B /* SoundEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = E242B7151E0E566B0047B33B /* SoundEngine.h */; settings = {ATTRIBUTES = (Public, ); }; }; 11 | E242B71F1E0E56E80047B33B /* SoundSFX.swift in Sources */ = {isa = PBXBuildFile; fileRef = E242B71D1E0E56E80047B33B /* SoundSFX.swift */; }; 12 | E242B7201E0E56E80047B33B /* SoundEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = E242B71E1E0E56E80047B33B /* SoundEngine.swift */; }; 13 | E242B7221E0E57050047B33B /* Int+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = E242B7211E0E57050047B33B /* Int+Extensions.swift */; }; 14 | /* End PBXBuildFile section */ 15 | 16 | /* Begin PBXFileReference section */ 17 | E242B7121E0E566B0047B33B /* SoundEngine.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SoundEngine.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 18 | E242B7151E0E566B0047B33B /* SoundEngine.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SoundEngine.h; sourceTree = ""; }; 19 | E242B7161E0E566B0047B33B /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 20 | E242B71D1E0E56E80047B33B /* SoundSFX.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SoundSFX.swift; sourceTree = ""; }; 21 | E242B71E1E0E56E80047B33B /* SoundEngine.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SoundEngine.swift; sourceTree = ""; }; 22 | E242B7211E0E57050047B33B /* Int+Extensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Int+Extensions.swift"; sourceTree = ""; }; 23 | /* End PBXFileReference section */ 24 | 25 | /* Begin PBXFrameworksBuildPhase section */ 26 | E242B70E1E0E566B0047B33B /* Frameworks */ = { 27 | isa = PBXFrameworksBuildPhase; 28 | buildActionMask = 2147483647; 29 | files = ( 30 | ); 31 | runOnlyForDeploymentPostprocessing = 0; 32 | }; 33 | /* End PBXFrameworksBuildPhase section */ 34 | 35 | /* Begin PBXGroup section */ 36 | E242B7081E0E566B0047B33B = { 37 | isa = PBXGroup; 38 | children = ( 39 | E242B7141E0E566B0047B33B /* SoundEngine */, 40 | E242B7131E0E566B0047B33B /* Products */, 41 | ); 42 | sourceTree = ""; 43 | }; 44 | E242B7131E0E566B0047B33B /* Products */ = { 45 | isa = PBXGroup; 46 | children = ( 47 | E242B7121E0E566B0047B33B /* SoundEngine.framework */, 48 | ); 49 | name = Products; 50 | sourceTree = ""; 51 | }; 52 | E242B7141E0E566B0047B33B /* SoundEngine */ = { 53 | isa = PBXGroup; 54 | children = ( 55 | E242B7151E0E566B0047B33B /* SoundEngine.h */, 56 | E242B71D1E0E56E80047B33B /* SoundSFX.swift */, 57 | E242B71E1E0E56E80047B33B /* SoundEngine.swift */, 58 | E242B7211E0E57050047B33B /* Int+Extensions.swift */, 59 | E242B7161E0E566B0047B33B /* Info.plist */, 60 | ); 61 | path = SoundEngine; 62 | sourceTree = ""; 63 | }; 64 | /* End PBXGroup section */ 65 | 66 | /* Begin PBXHeadersBuildPhase section */ 67 | E242B70F1E0E566B0047B33B /* Headers */ = { 68 | isa = PBXHeadersBuildPhase; 69 | buildActionMask = 2147483647; 70 | files = ( 71 | E242B7171E0E566B0047B33B /* SoundEngine.h in Headers */, 72 | ); 73 | runOnlyForDeploymentPostprocessing = 0; 74 | }; 75 | /* End PBXHeadersBuildPhase section */ 76 | 77 | /* Begin PBXNativeTarget section */ 78 | E242B7111E0E566B0047B33B /* SoundEngine */ = { 79 | isa = PBXNativeTarget; 80 | buildConfigurationList = E242B71A1E0E566B0047B33B /* Build configuration list for PBXNativeTarget "SoundEngine" */; 81 | buildPhases = ( 82 | E242B70D1E0E566B0047B33B /* Sources */, 83 | E242B70E1E0E566B0047B33B /* Frameworks */, 84 | E242B70F1E0E566B0047B33B /* Headers */, 85 | E242B7101E0E566B0047B33B /* Resources */, 86 | ); 87 | buildRules = ( 88 | ); 89 | dependencies = ( 90 | ); 91 | name = SoundEngine; 92 | productName = SoundEngine; 93 | productReference = E242B7121E0E566B0047B33B /* SoundEngine.framework */; 94 | productType = "com.apple.product-type.framework"; 95 | }; 96 | /* End PBXNativeTarget section */ 97 | 98 | /* Begin PBXProject section */ 99 | E242B7091E0E566B0047B33B /* Project object */ = { 100 | isa = PBXProject; 101 | attributes = { 102 | LastUpgradeCheck = 0810; 103 | ORGANIZATIONNAME = "Endless Wave Software"; 104 | TargetAttributes = { 105 | E242B7111E0E566B0047B33B = { 106 | CreatedOnToolsVersion = 8.1; 107 | DevelopmentTeam = PNK557J4EE; 108 | LastSwiftMigration = 0810; 109 | ProvisioningStyle = Automatic; 110 | }; 111 | }; 112 | }; 113 | buildConfigurationList = E242B70C1E0E566B0047B33B /* Build configuration list for PBXProject "SoundEngine" */; 114 | compatibilityVersion = "Xcode 3.2"; 115 | developmentRegion = English; 116 | hasScannedForEncodings = 0; 117 | knownRegions = ( 118 | en, 119 | ); 120 | mainGroup = E242B7081E0E566B0047B33B; 121 | productRefGroup = E242B7131E0E566B0047B33B /* Products */; 122 | projectDirPath = ""; 123 | projectRoot = ""; 124 | targets = ( 125 | E242B7111E0E566B0047B33B /* SoundEngine */, 126 | ); 127 | }; 128 | /* End PBXProject section */ 129 | 130 | /* Begin PBXResourcesBuildPhase section */ 131 | E242B7101E0E566B0047B33B /* Resources */ = { 132 | isa = PBXResourcesBuildPhase; 133 | buildActionMask = 2147483647; 134 | files = ( 135 | ); 136 | runOnlyForDeploymentPostprocessing = 0; 137 | }; 138 | /* End PBXResourcesBuildPhase section */ 139 | 140 | /* Begin PBXSourcesBuildPhase section */ 141 | E242B70D1E0E566B0047B33B /* Sources */ = { 142 | isa = PBXSourcesBuildPhase; 143 | buildActionMask = 2147483647; 144 | files = ( 145 | E242B7221E0E57050047B33B /* Int+Extensions.swift in Sources */, 146 | E242B71F1E0E56E80047B33B /* SoundSFX.swift in Sources */, 147 | E242B7201E0E56E80047B33B /* SoundEngine.swift in Sources */, 148 | ); 149 | runOnlyForDeploymentPostprocessing = 0; 150 | }; 151 | /* End PBXSourcesBuildPhase section */ 152 | 153 | /* Begin XCBuildConfiguration section */ 154 | E242B7181E0E566B0047B33B /* Debug */ = { 155 | isa = XCBuildConfiguration; 156 | buildSettings = { 157 | ALWAYS_SEARCH_USER_PATHS = NO; 158 | CLANG_ANALYZER_NONNULL = YES; 159 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 160 | CLANG_CXX_LIBRARY = "libc++"; 161 | CLANG_ENABLE_MODULES = YES; 162 | CLANG_ENABLE_OBJC_ARC = YES; 163 | CLANG_WARN_BOOL_CONVERSION = YES; 164 | CLANG_WARN_CONSTANT_CONVERSION = YES; 165 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 166 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 167 | CLANG_WARN_EMPTY_BODY = YES; 168 | CLANG_WARN_ENUM_CONVERSION = YES; 169 | CLANG_WARN_INFINITE_RECURSION = YES; 170 | CLANG_WARN_INT_CONVERSION = YES; 171 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 172 | CLANG_WARN_SUSPICIOUS_MOVES = YES; 173 | CLANG_WARN_UNREACHABLE_CODE = YES; 174 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 175 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 176 | COPY_PHASE_STRIP = NO; 177 | CURRENT_PROJECT_VERSION = 1; 178 | DEBUG_INFORMATION_FORMAT = dwarf; 179 | ENABLE_STRICT_OBJC_MSGSEND = YES; 180 | ENABLE_TESTABILITY = YES; 181 | GCC_C_LANGUAGE_STANDARD = gnu99; 182 | GCC_DYNAMIC_NO_PIC = NO; 183 | GCC_NO_COMMON_BLOCKS = YES; 184 | GCC_OPTIMIZATION_LEVEL = 0; 185 | GCC_PREPROCESSOR_DEFINITIONS = ( 186 | "DEBUG=1", 187 | "$(inherited)", 188 | ); 189 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 190 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 191 | GCC_WARN_UNDECLARED_SELECTOR = YES; 192 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 193 | GCC_WARN_UNUSED_FUNCTION = YES; 194 | GCC_WARN_UNUSED_VARIABLE = YES; 195 | IPHONEOS_DEPLOYMENT_TARGET = 10.1; 196 | MTL_ENABLE_DEBUG_INFO = YES; 197 | ONLY_ACTIVE_ARCH = YES; 198 | SDKROOT = iphoneos; 199 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; 200 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 201 | TARGETED_DEVICE_FAMILY = "1,2"; 202 | VERSIONING_SYSTEM = "apple-generic"; 203 | VERSION_INFO_PREFIX = ""; 204 | }; 205 | name = Debug; 206 | }; 207 | E242B7191E0E566B0047B33B /* Release */ = { 208 | isa = XCBuildConfiguration; 209 | buildSettings = { 210 | ALWAYS_SEARCH_USER_PATHS = NO; 211 | CLANG_ANALYZER_NONNULL = YES; 212 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 213 | CLANG_CXX_LIBRARY = "libc++"; 214 | CLANG_ENABLE_MODULES = YES; 215 | CLANG_ENABLE_OBJC_ARC = YES; 216 | CLANG_WARN_BOOL_CONVERSION = YES; 217 | CLANG_WARN_CONSTANT_CONVERSION = YES; 218 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 219 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 220 | CLANG_WARN_EMPTY_BODY = YES; 221 | CLANG_WARN_ENUM_CONVERSION = YES; 222 | CLANG_WARN_INFINITE_RECURSION = YES; 223 | CLANG_WARN_INT_CONVERSION = YES; 224 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 225 | CLANG_WARN_SUSPICIOUS_MOVES = YES; 226 | CLANG_WARN_UNREACHABLE_CODE = YES; 227 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 228 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 229 | COPY_PHASE_STRIP = NO; 230 | CURRENT_PROJECT_VERSION = 1; 231 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 232 | ENABLE_NS_ASSERTIONS = NO; 233 | ENABLE_STRICT_OBJC_MSGSEND = YES; 234 | GCC_C_LANGUAGE_STANDARD = gnu99; 235 | GCC_NO_COMMON_BLOCKS = YES; 236 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 237 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 238 | GCC_WARN_UNDECLARED_SELECTOR = YES; 239 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 240 | GCC_WARN_UNUSED_FUNCTION = YES; 241 | GCC_WARN_UNUSED_VARIABLE = YES; 242 | IPHONEOS_DEPLOYMENT_TARGET = 10.1; 243 | MTL_ENABLE_DEBUG_INFO = NO; 244 | SDKROOT = iphoneos; 245 | SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; 246 | TARGETED_DEVICE_FAMILY = "1,2"; 247 | VALIDATE_PRODUCT = YES; 248 | VERSIONING_SYSTEM = "apple-generic"; 249 | VERSION_INFO_PREFIX = ""; 250 | }; 251 | name = Release; 252 | }; 253 | E242B71B1E0E566B0047B33B /* Debug */ = { 254 | isa = XCBuildConfiguration; 255 | buildSettings = { 256 | CLANG_ENABLE_MODULES = YES; 257 | CODE_SIGN_IDENTITY = ""; 258 | DEFINES_MODULE = YES; 259 | DEVELOPMENT_TEAM = PNK557J4EE; 260 | DYLIB_COMPATIBILITY_VERSION = 1; 261 | DYLIB_CURRENT_VERSION = 1; 262 | DYLIB_INSTALL_NAME_BASE = "@rpath"; 263 | INFOPLIST_FILE = SoundEngine/Info.plist; 264 | INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; 265 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 266 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 267 | PRODUCT_BUNDLE_IDENTIFIER = com.endlesswavesoftware.SoundEngine; 268 | PRODUCT_NAME = "$(TARGET_NAME)"; 269 | SKIP_INSTALL = YES; 270 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 271 | SWIFT_VERSION = 3.0; 272 | }; 273 | name = Debug; 274 | }; 275 | E242B71C1E0E566B0047B33B /* Release */ = { 276 | isa = XCBuildConfiguration; 277 | buildSettings = { 278 | CLANG_ENABLE_MODULES = YES; 279 | CODE_SIGN_IDENTITY = ""; 280 | DEFINES_MODULE = YES; 281 | DEVELOPMENT_TEAM = PNK557J4EE; 282 | DYLIB_COMPATIBILITY_VERSION = 1; 283 | DYLIB_CURRENT_VERSION = 1; 284 | DYLIB_INSTALL_NAME_BASE = "@rpath"; 285 | INFOPLIST_FILE = SoundEngine/Info.plist; 286 | INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; 287 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 288 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 289 | PRODUCT_BUNDLE_IDENTIFIER = com.endlesswavesoftware.SoundEngine; 290 | PRODUCT_NAME = "$(TARGET_NAME)"; 291 | SKIP_INSTALL = YES; 292 | SWIFT_VERSION = 3.0; 293 | }; 294 | name = Release; 295 | }; 296 | /* End XCBuildConfiguration section */ 297 | 298 | /* Begin XCConfigurationList section */ 299 | E242B70C1E0E566B0047B33B /* Build configuration list for PBXProject "SoundEngine" */ = { 300 | isa = XCConfigurationList; 301 | buildConfigurations = ( 302 | E242B7181E0E566B0047B33B /* Debug */, 303 | E242B7191E0E566B0047B33B /* Release */, 304 | ); 305 | defaultConfigurationIsVisible = 0; 306 | defaultConfigurationName = Release; 307 | }; 308 | E242B71A1E0E566B0047B33B /* Build configuration list for PBXNativeTarget "SoundEngine" */ = { 309 | isa = XCConfigurationList; 310 | buildConfigurations = ( 311 | E242B71B1E0E566B0047B33B /* Debug */, 312 | E242B71C1E0E566B0047B33B /* Release */, 313 | ); 314 | defaultConfigurationIsVisible = 0; 315 | defaultConfigurationName = Release; 316 | }; 317 | /* End XCConfigurationList section */ 318 | }; 319 | rootObject = E242B7091E0E566B0047B33B /* Project object */; 320 | } 321 | -------------------------------------------------------------------------------- /SoundEngine/SoundEngine.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /SoundEngine/SoundEngine/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 1.2 19 | CFBundleVersion 20 | $(CURRENT_PROJECT_VERSION) 21 | NSPrincipalClass 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /SoundEngine/SoundEngine/Int+Extensions.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Int+Extensions.swift 3 | // 4 | // Created by Tom Kier on 12/21/16. 5 | // Copyright © 2016 Endless Wave Software LLC. All rights reserved. 6 | // 7 | // Licensed under the Apache License, Version 2.0 (the "License"); 8 | // you may not use this file except in compliance with the License. 9 | // You may obtain a copy of the License at 10 | // 11 | // http://www.apache.org/licenses/LICENSE-2.0 12 | // 13 | // Unless required by applicable law or agreed to in writing, software 14 | // distributed under the License is distributed on an "AS IS" BASIS, 15 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | // See the License for the specific language governing permissions and 17 | // limitations under the License. 18 | 19 | import CoreGraphics 20 | 21 | public extension Int { 22 | 23 | /// Returns a random integer between 0 and n-1. 24 | public static func random(_ n: Int) -> Int { 25 | return Int(arc4random_uniform(UInt32(n))) 26 | } 27 | 28 | /// Returns a random integer in the range min...max, inclusive. 29 | public static func random(min: Int, max: Int) -> Int { 30 | assert(min < max) 31 | return Int(arc4random_uniform(UInt32(max - min + 1))) + min 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /SoundEngine/SoundEngine/SoundEngine.h: -------------------------------------------------------------------------------- 1 | // 2 | // SoundEngine.h 3 | // SoundEngine 4 | // 5 | // Created by Tom Kier on 12/23/16. 6 | // Copyright © 2016 Endless Wave Software LLC. All rights reserved. 7 | // 8 | // Licensed under the Apache License, Version 2.0 (the "License"); 9 | // you may not use this file except in compliance with the License. 10 | // You may obtain a copy of the License at 11 | // 12 | // http://www.apache.org/licenses/LICENSE-2.0 13 | // 14 | // Unless required by applicable law or agreed to in writing, software 15 | // distributed under the License is distributed on an "AS IS" BASIS, 16 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | // See the License for the specific language governing permissions and 18 | // limitations under the License. 19 | 20 | #import 21 | 22 | //! Project version number for SoundEngine. 23 | FOUNDATION_EXPORT double SoundEngineVersionNumber; 24 | 25 | //! Project version string for SoundEngine. 26 | FOUNDATION_EXPORT const unsigned char SoundEngineVersionString[]; 27 | 28 | // In this header, you should import all the public headers of your framework using statements like #import 29 | 30 | 31 | -------------------------------------------------------------------------------- /SoundEngine/SoundEngine/SoundEngine.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SoundEngine.swift 3 | // 4 | // Created by Tom Kier on 12/21/16. 5 | // Copyright © 2016 Endless Wave Software LLC. All rights reserved. 6 | // 7 | // Licensed under the Apache License, Version 2.0 (the "License"); 8 | // you may not use this file except in compliance with the License. 9 | // You may obtain a copy of the License at 10 | // 11 | // http://www.apache.org/licenses/LICENSE-2.0 12 | // 13 | // Unless required by applicable law or agreed to in writing, software 14 | // distributed under the License is distributed on an "AS IS" BASIS, 15 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | // See the License for the specific language governing permissions and 17 | // limitations under the License. 18 | 19 | import Foundation 20 | import AVFoundation 21 | 22 | /// A simple, easy to use sound engine designed for iOS games 23 | public class SoundEngine { 24 | 25 | public static let shared = SoundEngine() 26 | 27 | private let engine = AVAudioEngine() 28 | private let backgroundMusicPlayer = AVAudioPlayerNode() 29 | private let sfxMixer = AVAudioMixerNode() 30 | private var alreadyStarted = false 31 | 32 | private var numSFXPlayers = 20 33 | private var playerNodes = [AVAudioPlayerNode]() 34 | private var pitchNodes = [AVAudioUnitTimePitch]() 35 | private var activePlayerIndex = 0 36 | 37 | private var fadeOutDisplayLink : CADisplayLink? 38 | private var fadeOutStartTime = 0.0 39 | private var fadeOutStartVolume = 1.0 40 | private let fadeOutLength = 1.5 41 | 42 | private init() { } 43 | 44 | /// Volume control for background music. Valid values are 0.0 - 1.0 45 | public var backgroundMusicVolume: Float = 1.0 { 46 | didSet { 47 | backgroundMusicPlayer.volume = backgroundMusicVolume 48 | } 49 | } 50 | 51 | /// Master volume for all sound effects. Valid values are 0.0 - 1.0 52 | public var sfxVolume: Float = 1.0 { 53 | didSet { 54 | sfxMixer.outputVolume = sfxVolume 55 | } 56 | } 57 | 58 | /** 59 | 60 | Configures the app's audio session and starts the sound engine. Should be called once, 61 | early during app start up, typically in the AppDelegate didFinishLaunchingWithOptions 62 | 63 | - Parameter numSFXPlayers: Specifies the number of sound effect players configured for playback. If your game needs to 64 | play large numbers of sounds simultaneously you may need to increase this number. The sound 65 | engine will let you know if numSFXPlayers needs to be increased by displaying the following 66 | message in the console: "All sfx players are busy. Increase numSFXPlayers in startEngine call" 67 | 68 | */ 69 | public func startEngine(numSFXPlayers: Int = 20) { 70 | 71 | if alreadyStarted { return } 72 | alreadyStarted = true 73 | 74 | configureAudioSession() 75 | 76 | engine.attach(backgroundMusicPlayer) 77 | engine.connect(backgroundMusicPlayer, to: engine.mainMixerNode, format: nil) 78 | 79 | engine.attach(sfxMixer) 80 | engine.connect(sfxMixer, to: engine.mainMixerNode, format: nil) 81 | 82 | self.numSFXPlayers = numSFXPlayers 83 | for _ in 0.. Void { 223 | 224 | guard let userInfo = notification.userInfo, 225 | let audioHintType = userInfo[AVAudioSessionSilenceSecondaryAudioHintTypeKey] as? UInt, 226 | let audioHint = AVAudioSessionSilenceSecondaryAudioHintType(rawValue:audioHintType) 227 | else { return } 228 | 229 | switch audioHint { 230 | case .begin: 231 | backgroundMusicPlayer.volume = 0.0 232 | break 233 | case .end: 234 | backgroundMusicPlayer.volume = backgroundMusicVolume 235 | break 236 | } 237 | } 238 | 239 | private func catchAudioSessionInterruptionNotification(notification:Notification) -> Void { 240 | 241 | guard let userInfo = notification.userInfo, 242 | let interruptionType = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt, 243 | let interruption = AVAudioSessionInterruptionType(rawValue:interruptionType) 244 | else { return } 245 | 246 | switch interruption { 247 | case .began: 248 | engine.pause() 249 | break 250 | case .ended: 251 | restartEngine() 252 | break 253 | } 254 | } 255 | 256 | private func catchDidBecomeActiveNotification(notification:Notification) -> Void { 257 | 258 | restartEngine() 259 | } 260 | 261 | private func restartEngine() { 262 | 263 | if !engine.isRunning { 264 | do { 265 | try engine.start() 266 | } catch { 267 | print("AVAudioEngine did not start") 268 | } 269 | } 270 | 271 | if AVAudioSession.sharedInstance().secondaryAudioShouldBeSilencedHint { 272 | backgroundMusicPlayer.volume = 0.0 273 | } else { 274 | backgroundMusicPlayer.volume = backgroundMusicVolume 275 | } 276 | } 277 | 278 | internal func loadSound(soundFile: String, 279 | volume: Float, 280 | volumeVary: Float? = nil, 281 | pitchVary: Float? = nil, 282 | completionHandler: @escaping ((() -> Void)?) -> Void) 283 | { 284 | var playClosure : (() -> Void)? = nil 285 | 286 | if !alreadyStarted { 287 | startEngine() 288 | } 289 | 290 | DispatchQueue.global(qos: .userInitiated).async { [weak self] in 291 | 292 | if let path = Bundle.main.path(forResource: soundFile, ofType: nil) { 293 | let fileURL = NSURL.fileURL(withPath: path) 294 | 295 | if let file = try? AVAudioFile(forReading: fileURL) { 296 | let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length)) 297 | do { 298 | try file.read(into: buffer) 299 | } catch _ { 300 | completionHandler(nil) 301 | return 302 | } 303 | 304 | var maxVolume : Float? 305 | var minVolume : Float? 306 | if let db = volumeVary { 307 | maxVolume = round(1000000000.0 * pow(10.0, db/20.0)) / 1000000000.0 308 | minVolume = round(1000000000.0 * pow(10.0, -db/20.0)) / 1000000000.0 309 | } 310 | 311 | playClosure = { [weak self] in 312 | self?.playBufferOnNextAvailablePlayer(buffer: buffer, 313 | volume: volume, 314 | minVolume: minVolume, 315 | maxVolume: maxVolume, 316 | pitchVary: pitchVary) 317 | } 318 | } 319 | } 320 | 321 | DispatchQueue.main.async { 322 | completionHandler(playClosure) 323 | } 324 | } 325 | } 326 | 327 | private func playBufferOnNextAvailablePlayer(buffer: AVAudioPCMBuffer, 328 | volume: Float, 329 | minVolume : Float?, 330 | maxVolume : Float?, 331 | pitchVary: Float?) 332 | { 333 | var numPlayersChecked = 0 334 | var player = playerNodes[activePlayerIndex] 335 | while player.isPlaying { 336 | activePlayerIndex += 1 337 | if activePlayerIndex == numSFXPlayers { 338 | activePlayerIndex = 0 339 | } 340 | player = playerNodes[activePlayerIndex] 341 | 342 | numPlayersChecked += 1 343 | if numPlayersChecked > numSFXPlayers { 344 | print("All sfx players are busy. Increase numSFXPlayers in startEngine call") 345 | return 346 | } 347 | } 348 | 349 | if let min = minVolume, let max = maxVolume { 350 | player.volume = volume * Float(Int.random(min: Int(min * 100), max: Int(max * 100))) / 100.0 351 | } else { 352 | player.volume = volume 353 | } 354 | 355 | let pitch = pitchNodes[activePlayerIndex] 356 | if !player.outputFormat(forBus: 0).isEqual(buffer.format) { 357 | engine.disconnectNodeOutput(pitch) 358 | engine.disconnectNodeOutput(player) 359 | engine.connect(player, to: pitch, format: buffer.format) 360 | engine.connect(pitch, to: sfxMixer, format: buffer.format) 361 | } 362 | 363 | if let cents = pitchVary { 364 | pitch.pitch = Float(Int.random(min: Int(-cents * 100.0), max: Int(cents * 100.0))) / 100.0 365 | pitch.bypass = false 366 | } else { 367 | pitch.bypass = true 368 | } 369 | 370 | player.scheduleBuffer(buffer, completionHandler:{ 371 | DispatchQueue.main.async { 372 | player.stop() 373 | } 374 | }) 375 | player.play() 376 | } 377 | 378 | private func loopBackgroundMusic(file: AVAudioFile) { 379 | 380 | backgroundMusicPlayer.scheduleFile(file, at: nil, completionHandler: { [weak self] in 381 | self?.loopBackgroundMusic(file: file) 382 | }) 383 | } 384 | 385 | private func loopRandomBackgroundMusic(file: AVAudioFile, soundFiles: [String]) { 386 | 387 | backgroundMusicPlayer.scheduleFile(file, at: nil, completionHandler: { [weak self] in 388 | let soundFile = soundFiles[Int.random(soundFiles.count)] 389 | if let path = Bundle.main.path(forResource: soundFile, ofType: nil) { 390 | let fileURL = NSURL.fileURL(withPath: path) 391 | if let file = try? AVAudioFile(forReading: fileURL) { 392 | self?.loopRandomBackgroundMusic(file: file, soundFiles: soundFiles) 393 | } 394 | } 395 | }) 396 | } 397 | 398 | private func startFadeOut() { 399 | 400 | stopFadeOut() 401 | 402 | fadeOutStartTime = CACurrentMediaTime() 403 | fadeOutStartVolume = Double(backgroundMusicPlayer.volume) 404 | 405 | fadeOutDisplayLink = CADisplayLink(target: self, selector: #selector(displayLinkDidFire)) 406 | fadeOutDisplayLink?.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode) 407 | } 408 | 409 | @objc private func displayLinkDidFire() { 410 | 411 | let elapsed = CACurrentMediaTime() - fadeOutStartTime 412 | 413 | if elapsed >= fadeOutLength { 414 | stopFadeOut() 415 | backgroundMusicPlayer.stop() 416 | return 417 | } 418 | 419 | let percentComplete = elapsed / fadeOutLength 420 | backgroundMusicPlayer.volume = Float(fadeOutStartVolume - fadeOutStartVolume * percentComplete) 421 | } 422 | 423 | private func stopFadeOut() { 424 | 425 | fadeOutDisplayLink?.invalidate() 426 | fadeOutDisplayLink = nil 427 | } 428 | } 429 | -------------------------------------------------------------------------------- /SoundEngine/SoundEngine/SoundSFX.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SoundSFX.swift 3 | // 4 | // Created by Tom Kier on 12/21/16. 5 | // Copyright © 2016 Endless Wave Software LLC. All rights reserved. 6 | // 7 | // Licensed under the Apache License, Version 2.0 (the "License"); 8 | // you may not use this file except in compliance with the License. 9 | // You may obtain a copy of the License at 10 | // 11 | // http://www.apache.org/licenses/LICENSE-2.0 12 | // 13 | // Unless required by applicable law or agreed to in writing, software 14 | // distributed under the License is distributed on an "AS IS" BASIS, 15 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | // See the License for the specific language governing permissions and 17 | // limitations under the License. 18 | 19 | import Foundation 20 | import SpriteKit 21 | 22 | public protocol PlayableSoundSFX { 23 | func play() 24 | } 25 | 26 | public let kVolumeVaryLow: Float = 1 // 1 db 27 | public let kVolumeVaryMedium: Float = 2 // 2 db 28 | public let kVolumeVaryLarge: Float = 3 // 3 db 29 | 30 | public let kPitchVaryLow: Float = 100 // 1 semitone 31 | public let kPitchVaryMedium: Float = 200 // 2 semitone 32 | public let kPitchVaryLarge: Float = 300 // 3 semitone 33 | 34 | /// Sound effect class for playing a short sound. 35 | open class SoundSFX : PlayableSoundSFX { 36 | 37 | private var playSound: (() -> Void)? 38 | private var playOnLoad = false 39 | 40 | /** 41 | 42 | Initializes a sound effect. When initialized loads the sound data from file and stores it into a buffer. The 43 | buffer is kept in memory for the lifetime of the SoundSFX object. The sound effect can play over and over, but 44 | its data is only loaded once at initialization time. 45 | 46 | - Parameters: 47 | - soundFile: The resource file that contains sound data (caf format recommneded) 48 | - volume: The base volume that the sound effect will be played at. Valid values are 0.0 - 1.0. 49 | - volumeVary: The amount the volume should randomly vary when played. Specified in dbs. 50 | - pitchVary: The amount the pitch should randomly vary when played. Specified in cents (1 musical semitone = 100 cents, 1 octave = 1200 cents). 51 | 52 | */ 53 | public init(_ soundFile: String, volume: Float = 1.0, volumeVary: Float? = nil, pitchVary: Float? = nil) { 54 | 55 | SoundEngine.shared.loadSound(soundFile: soundFile, 56 | volume: volume, 57 | volumeVary: volumeVary, 58 | pitchVary: pitchVary, 59 | completionHandler: { [weak self] playCallBack in 60 | guard let strongSelf = self else { return } 61 | strongSelf.playSound = playCallBack 62 | if strongSelf.playOnLoad, let play = playCallBack { 63 | play() 64 | } 65 | }) 66 | } 67 | 68 | /// Plays the sound effect. 69 | open func play() { 70 | if let playSound = playSound { 71 | playSound() 72 | } else { 73 | playOnLoad = true 74 | } 75 | } 76 | } 77 | 78 | /// A sound effect class that randomly plays a sound effect from a list of sound effects. 79 | open class RandomSoundSFX : PlayableSoundSFX { 80 | 81 | private var effects : [SoundSFX] 82 | 83 | /** 84 | 85 | Creates a playable sound effect that randomly plays one sound effect from a list of sound effects. Each time 86 | this sound effect is played it randony selects one of SoundSFX objects from the list of effects specified in the 87 | initailizer and plays that effect. 88 | 89 | - Parameter effects: Array of SoundSFX ojbects 90 | 91 | */ 92 | public init(_ effects: [SoundSFX]) { 93 | self.effects = effects 94 | } 95 | 96 | /// Plays the sound effect. 97 | open func play() { 98 | effects[Int.random(effects.count)].play() 99 | } 100 | } 101 | 102 | public extension SKAction { 103 | 104 | /** 105 | 106 | Creates a SKAction that when run will play a SoundSFX or RandomSoundSFX object. 107 | 108 | - Parameter soundSFX: The SoundSFX or RandomSoundSFX object to be played. 109 | 110 | */ 111 | public class func playSoundSFX(_ soundSFX: PlayableSoundSFX) -> SKAction { 112 | return SKAction.run({ 113 | soundSFX.play() 114 | }) 115 | } 116 | } 117 | 118 | --------------------------------------------------------------------------------