iPhone教程 播放音效檔是本文要介紹的內容,本文示範如何使用Objective-C開發播放mp3檔案的iPhone程式,當然本文目的不是要讓你做一個iPhone版的播放器,因為這根本用不著你,iPod程式已經很好了。本文的目的是要讓你能夠在自己的遊戲中使用音樂。
如下:
1.開啟xcode,建立一個名為TalkingDemo的View-based Application類型的iPhone程式。
2.如果要使用播放聲音的功能,一定要引入AVFoundation庫,右擊項目中的Frameworkds目錄,從菜單中選擇Add->Existing Frameworkd,所示:
此操作將開啟瀏覽庫的對話方塊,我們選擇名為AVFoundation.framework的庫,並把它添加進來。
3.修改TalkingDemoViewController.h檔案內容如下:
- #import <UIKit/UIKit.h>
- #import <AVFoundation/AVFoundation.h>
-
- @interface TalkingDemoViewController : UIViewController {
- AVAudioPlayer *player;
-
- }
-
- -(IBAction)sayTalking:(id)sender;
- @end
4.雙擊TalkingDemoViewController.xib檔案開啟InterfaceBuilder,拖入一個Round Rect Button組件,並將這個組件分別綁定為btn如果你還不會綁定InterfaceBuilder組件到Objective-C代碼,請看iPhone按鈕的使用),然後將按鈕的標籤修改為“播放音樂”
5.修改TalkingDemoViewController.m檔案的內容如下所示:
- #import "TalkingDemoViewController.h"
-
- @implementation TalkingDemoViewController
- // Implement viewDidLoad to do additiona l setup after loading the view, typically from a nib.
- - (void)viewDidLoad {
- if (player) {
- [player release];
- }
- NSString *soundPath=[[NSBundle mainBundle] pathForResource:@"intro" ofType:@"caf"];
- NSURL *soundUrl=[[NSURL alloc] initFileURLWithPath:soundPath];
- player=[[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
- [player prepareToPlay];
- [soundUrl release];
- [super viewDidLoad];
- }
-
- -(IBAction)sayTalking:(id)sender
- {
- NSLog(@"播放聲音");
- [player play];
-
- }
- // Override to allow orientations other than the default portrait orientation.
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
- return YES;
- }
-
- - (void)didReceiveMemoryWarning {
- // Releases the view if it doesn’t have a superview.
- [super didReceiveMemoryWarning];
- // Release any cached data, images, etc that aren’t in use.
- }
-
- - (void)viewDidUnload {
- // Release any retained subviews of the main view.
- // e.g. self.myOutlet = nil;
- }
-
- - (void)dealloc {
- [player release];
- [super dealloc];
- }
- @end
6.此代碼將播放一個名為 “intro.caf”的檔案,請將這個檔案加入到資源檔夾(Resources)中.
7.按Command+R運行此程式,嘗試驗擊“播放音樂”按鈕,就可以聽到播放的聲音了。
原始碼:http://easymorse-android.googlecode.com/svn/trunk/TalkingDemo/
小結:iPhone教程 播放音效檔得到內容介紹我那了,希望本文對你有所協助。
本文