Skip to content

Instantly share code, notes, and snippets.

@amrangry
Last active April 12, 2020 08:58
Show Gist options
  • Save amrangry/e1a889c005b5a3e52a5724b05aa6a7b9 to your computer and use it in GitHub Desktop.
Save amrangry/e1a889c005b5a3e52a5724b05aa6a7b9 to your computer and use it in GitHub Desktop.
A SoundPlayer is a handler controller object used to manage the playback of a media asset which You can use to play media assets
//
// SoundPlayer.swift
// Logistics
//
// Created by AmrAngry on 26/02/2020.
// Copyright © 2020 ADKATech.com All rights reserved.
// A SoundPlayer is a handler controller object used to manage the playback of a media asset which You can use to play media assets
// https://gist.github.com/amrangry/e1a889c005b5a3e52a5724b05aa6a7b9
import Foundation
import AVFoundation
enum SoundPlayerType {
case warning
case done
}
/// A SoundPlayer is a handler controller object used to manage the playback of a media asset.
/// You can use an AVPlayer to play local file-based media, such as MP3 audio files.
/// SoundPlayer is for playing a single media asset at a time.
/// You use a SoundPlayer to play media assets
/// Playing Sound can be done by calling the SoundPlayer - SoundManager.
/// SoundPlayer().playSound(.warning)
class SoundPlayer {
//MARK: - Varibles
private var player: AVAudioPlayer?
func playSound(_ sound: SoundPlayerType) {
if sound == .warning {
playSound(sound: "warningBeep")
} else if sound == .done {
playSound(sound: "beep-06")
}
}
func playSound(sound: String) {
guard let url = Bundle.main.url(forResource: sound, withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
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.wav.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
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