-
-
Save byaruhaf/e6944be1df4a91d2d1a5e9213e3a99ef to your computer and use it in GitHub Desktop.
Play an audio file from resources or .xcassets
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
import AVFoundation | |
var audioPlayer: AVAudioPlayer? | |
enum AudioLoader { | |
case fromResource(URL) | |
case fromAsset(NSDataAsset) | |
} | |
enum AudioLoaderError: Error { | |
case resourceNotFound | |
case assetNotFound | |
case loadPlayer | |
} | |
func playFromResources(filename: String, fileExtension: String) throws { | |
guard let url = Bundle.main.url(forResource: filename, withExtension: fileExtension) else { | |
throw AudioLoaderError.resourceNotFound | |
} | |
try playFrom(audioLoader: AudioLoader.fromResource(url)) | |
} | |
func playFromAssets(filename: String) throws { | |
guard let dataAsset = NSDataAsset(name: filename) else { | |
throw AudioLoaderError.assetNotFound | |
} | |
try playFrom(audioLoader: AudioLoader.fromAsset(dataAsset)) | |
} | |
func playFrom(audioLoader: AudioLoader) throws { | |
switch audioLoader { | |
case .fromResource(let url): | |
audioPlayer = try perform(AVAudioPlayer(contentsOf: url), | |
orThrow: AudioLoaderError.loadPlayer) | |
case .fromAsset(let dataAsset): | |
audioPlayer = try perform(AVAudioPlayer(data: dataAsset.data, fileTypeHint: AVFileTypeWAVE), | |
orThrow: AudioLoaderError.loadPlayer) | |
} | |
DispatchQueue.global(qos: .userInitiated).async { | |
audioPlayer?.play() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment