本文转自:http://plter.com/?p=354
本文演示如何使用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/