Background
In this lesson, you can learn:- AVAudioPlayer class in AV Foundation Framework
- UIButton object
Based on the Lesson #7 - Simple Animation, we added the audio effect on the animation.
iOS provides many different methods for playing audio, AV Foundation framework is one of popular one to provide AVAudioPlayer class.The AVFoundation framework in iOS can be used to play, edit and record audio and video. Let's start to play!iOS can support fhe following audio formats:
- .caf
- .m4a
- .aif, .aiff
- .mp3
Step#1: To add audio files into the project
Step#2: To add AV Foundation framework
1. By default, no AV Foundation framework does not exist, so we have to add it manually.
2. Click the Project Name in "Project Navigator", switch to "Build Phases" and expand "Link Binary With Libraries (3 items)".
3. After added, you can find "Foundation.framework" under the group "Frameworks".
Step#3: To setup a new AVAudioPlayer object
Follow the Practice #4b - 3 Steps for setup Object to setup a new UI object.<Step #1 - .h file>
1. In the project navigator, click "xxxViewController.h" and edit the code like this in order to declare a new AVAudioPlayer object:
Notes:
- Since AVFoundation framework is an external one, so have to import it manually.
- <AVFoundation/AVFoundation.h> means that include all classes inside AVFoundation framework.
<Step #2 - .m file>
2. Then, click "xxxViewController.m" and edit the code for "@synthesize" the AVAudioPlayer object like this:
* Notes:
- Since we need to click the button with action, so set (IBAction).
- 畫面見到的話, 到Step 3 做 connection.
- 畫面唔見到的話, 到Step 3 做 alloc.
- NSURL fileURLWithPath:@"...." VS fileURLWithString:@"...".
- setNumberOfLoops:10 <-- Play 11 times.
<Step #3b - Storyboard file>
1. Add a "Toolbar" object onto storyboard and change the bar button label as "Play Sound".
2. In tab "Connections", click the yellow button (i.e. View Controller) at the bottom and then drag the "playSound:" to the bar button object in View to do connection.
Step# 4:Compile & Run
Step#5: Enhancement
<Step #2 - .m file>1. Add 2 more IBAction actions in xxxViewController.m like this:
1. Drag 2 more "Bar button item" objects into the Toolbar and add 2 "Flexible Space Bar Button item" to split out these three buttons.
2. Click once on the toolbar item can select the "Toolbar" in Attribute.
3. Click one more time on the tool bar item can select the "Bar Button item" in Attribute. Change the identifier of these three buttons as "Play", "Pause" and "Stop" like this:
4. Do connection between objects and actions.
Step#6: Compile & Run
1. Something gets strange:
2.Correct the code in xxxViewController.m like this:
Reference
- Developer Library
- iOS Developer Zone
- iOSCreator
No comments:
Post a Comment