Thursday, June 25, 2015

Playing sound using Swift

Posting small code snippet to that shows how to play sound using Swift in iOS.

First we need to import AVFoundation.
import AVFoundation
Then we need to create instance of AVAudioPlayer. I created a small utility function like below for the same.

private static func createAudioPlayer
( sound: String, type: String ) -> AVAudioPlayer {

    var error:NSError?;
    let soundUrl = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: type)!);
    println(soundUrl)
    
    var player = AVAudioPlayer(contentsOfURL: soundUrl, error: &error);
    player.prepareToPlay();
    return player;
}

And this function can be used like below.
public init() {
    // Removed deprecated use of AVAudioSessionDelegate protocol
    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil);
    AVAudioSession.sharedInstance().setActive(true, error: nil);
    
    correctAns = MusicHelper.createAudioPlayer("correctAns", type: "wav");
    wrongAns = MusicHelper.createAudioPlayer("wrongAns",type: "wav");
}
Now we can use AVAudioPlayer's play API to play the sound. Like below.

public func playCorrectAnsSound() {
    correctAns.play();
}

public func playWrongAnsSound() {
    wrongAns.play();
}

That's it, thanks for reading.

No comments:

Post a Comment