iPhone教程 播放聲音文件
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教程 播放聲音文件得到內容介紹我那了,希望本文對你有所幫助。
本文轉自:http://plter.com/?p=354