Created
May 6, 2017 18:24
-
-
Save tikipatel/174742447c11b279c3e28a04da7018c9 to your computer and use it in GitHub Desktop.
Select a sound to play from a picker view
This file contains 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 UIKit | |
import AVFoundation | |
class SoundViewController: UIViewController { | |
var sounds: [String] = ["island", "jingle", "starwars", "wind", "does_no_exist"] // Files that will possibly available to paly | |
var selectedSoundString: String? = nil | |
var player: AVAudioPlayer? | |
@IBAction func play(_ sender: Any) { | |
guard let selectedSoundString = selectedSoundString else { | |
print("No selected sound to play...") | |
return | |
} | |
guard let soundData = NSDataAsset(name: selectedSoundString) else { | |
print("Asset is missing") | |
return | |
} | |
do { | |
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) | |
try AVAudioSession.sharedInstance().setActive(true) | |
player = try AVAudioPlayer(data: soundData.data, fileTypeHint: AVFileTypeWAVE) | |
player?.play() | |
} catch { | |
print(error) | |
} | |
} | |
@IBAction func stop(_ sender: Any) { | |
player?.stop() | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
selectedSoundString = sounds.first // picker view will always load with the first one selected, so let's just set the selected sound string now | |
} | |
} | |
extension SoundViewController: UIPickerViewDataSource { | |
func numberOfComponents(in pickerView: UIPickerView) -> Int { | |
return 1 | |
} | |
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { | |
return sounds.count | |
} | |
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { | |
return sounds[row] | |
} | |
} | |
extension SoundViewController: UIPickerViewDelegate { | |
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { | |
selectedSoundString = sounds[row] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment