Today I did Lesson 3a in Udacity. The course Intro to iOS Development with Swift, is an introduction to iOS development but does assume basic programming knowledge (such as if statements, methods, etc.). It is an introduction to iOS programming and the Swift language. Thus, with my background, many of the topics have been a review but a few things have been new and helpful to me.
One of those things has been using AVAudioPlayer. I hadn't used audio files before and this project has allowed me to become more comfortable using them.
If you want to add an audio file, needs to be added to the Xcode project by clicking "File" and then on "Add File to 'Project Name'". There is no longer a "Supporting Files" folder so you can store you where you'd like to.
A Path must be created to access the file. Below is the code I use:
One of those things has been using AVAudioPlayer. I hadn't used audio files before and this project has allowed me to become more comfortable using them.
If you want to add an audio file, needs to be added to the Xcode project by clicking "File" and then on "Add File to 'Project Name'". There is no longer a "Supporting Files" folder so you can store you where you'd like to.
A Path must be created to access the file. Below is the code I use:
let path = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3")
This method stores the file as a string. It must be converted to an NSUrl object to use.
The Swift syntax for this is:
let fileUrl = NSURL(fileURLWithPath: path)
I created an AVAudioPlayer object outside of the viewDidLoad method so it could be accessed by my playQuoteQuickly and playQuoteSlowly methods.
To initiate an instance of the audioPlayer object, I used the following syntax which required a NSUrl item:
audioPlayer = try! AVAudioPlayer(contentsOfURL: fileUrl)
After that, to be able to change the speed of the audio, the rate property had to enabled and used. It was pretty simple:
audioPlayer.enableRate = true
That allows you to change speeds to anything between 0.5 and 2.0. (e.g. audioPlayer.rate = 2.0)
Anyway, it was fun to learn to use AVAudioPlayer, something that was new to me.
Documentation: https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerClassReference/index.html#//apple_ref/occ/instp/AVAudioPlayer/enableRate