iPhone教程 播放聲音文件
iPhone教程 播放聲音文件是本文要介紹的內(nèi)容,本文演示如何使用Objective-C開(kāi)發(fā)播放mp3文件的iPhone程序,當(dāng)然本文目的不是要讓你做一個(gè)iPhone版的播放器,因?yàn)檫@根本用不著你,iPod程序已經(jīng)很好了。本文的目的是要讓你能夠在自己的游戲中使用音樂(lè)。
效果圖如下:
1.打開(kāi)xcode,創(chuàng)建一個(gè)名為T(mén)alkingDemo的View-based Application類(lèi)型的iPhone程序。
2.如果要使用播放聲音的功能,一定要引入AVFoundation庫(kù),右擊項(xiàng)目中的Frameworkds目錄,從菜單中選擇Add->Existing Frameworkd,下圖所示:
此操作將打開(kāi)瀏覽庫(kù)的對(duì)話框,我們選擇名為AVFoundation.framework的庫(kù),并把它添加進(jìn)來(lái)。
3.修改TalkingDemoViewController.h文件內(nèi)容如下:
- #import <UIKit/UIKit.h>
- #import <AVFoundation/AVFoundation.h>
- @interface TalkingDemoViewController : UIViewController {
- AVAudioPlayer *player;
- }
- -(IBAction)sayTalking:(id)sender;
- @end
4.雙擊TalkingDemoViewController.xib文件打開(kāi)InterfaceBuilder,拖入一個(gè)Round Rect Button組件,并將這個(gè)組件分別綁定為btn(如果你還不會(huì)綁定InterfaceBuilder組件到Objective-C代碼,請(qǐng)看iPhone按鈕的使用),然后將按鈕的標(biāo)簽修改為“播放音樂(lè)”
5.修改TalkingDemoViewController.m文件的內(nèi)容如下所示:
- #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.此代碼將播放一個(gè)名為 “intro.caf”的文件,請(qǐng)將這個(gè)文件加入到資源文件夾(Resources)中.
7.按Command+R運(yùn)行此程序,嘗試點(diǎn)擊“播放音樂(lè)”按鈕,就可以聽(tīng)到播放的聲音了。
源代碼:http://easymorse-android.googlecode.com/svn/trunk/TalkingDemo/
小結(jié):iPhone教程 播放聲音文件得到內(nèi)容介紹我那了,希望本文對(duì)你有所幫助。
本文轉(zhuǎn)自:http://plter.com/?p=354