您的位置:首页 > 其它

iphone开发之多媒体播放参考源码

2012-08-13 14:29 288 查看
OSsdk中提供了很多方便的方法来播放多媒体。本文将利用这些SDK做一个demo,来讲述一下如何使用它们来播放音频文件。

AudioToolboxframework

使用AudioToolboxframework。这个框架可以将比较短的声音注册到
systemsound服务上。被注册到systemsound服务上的声音称之为
systemsounds。它必须满足下面几个条件。

1、播放的时间不能超过30秒

2、数据必须是PCM或者IMA4流格式

3、必须被打包成下面三个格式之一:CoreAudioFormat(.caf),Waveformaudio(.wav),或者
AudioInterchangeFile(.aiff)

声音文件必须放到设备的本地文件夹下面。通过AudioServicesCreateSystemSoundID方法注册这个声音文件,AudioServicesCreateSystemSoundID需要声音文件的url的CFURLRef对象。看下面注册代码:

#import<AudioToolbox/AudioToolbox.h>

@interfaceMediaPlayerViewController:UIViewController

{

IBOutletUIButton*audioButton;

SystemSoundIDshortSound;
}
-(id)init

{

self=[superinitWithNibName:@"MediaPlayerViewController"bundle:nil];

if(self){//GetthefullpathofSound12.aif

NSString*soundPath=[[NSBundlemainBundle]pathForResource:@"Sound12"

ofType:@"aif"];//Ifthisfileisactuallyinthebundle...

if(soundPath){//CreateafileURLwiththispath

NSURL*soundURL=[NSURLfileURLWithPath:soundPath];//RegistersoundfilelocatedatthatURLasasystemsound

OSStatuserr=AudioServicesCreateSystemSoundID((CFURLRef)soundURL,

&shortSound);

if(err!=kAudioServicesNoError)

NSLog(@"Couldnotload%@,errorcode:%d",soundURL,err);
}
}

returnself;
}
这样就可以使用下面代码播放声音了:

-(IBAction)playShortSound:(id)sender

{

AudioServicesPlaySystemSound(shortSound);
}
使用下面代码,还加一个震动的效果:

-(IBAction)playShortSound:(id)sender

{

AudioServicesPlaySystemSound(shortSound);

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
AVFoundationframework

对于压缩过Audio文件,或者超过30秒的音频文件,可以使用AVAudioPlayer类。这个类定义在AVFoundation
framework中。

下面我们使用这个类播放一个mp3的音频文件。首先要引入AVFoundation
framework,然后MediaPlayerViewController.h中添加下面代码:

#import<AVFoundation/AVFoundation.h>

@interfaceMediaPlayerViewController:UIViewController<AVAudioPlayerDelegate>

{

IBOutletUIButton*audioButton;

SystemSoundIDshortSound;

AVAudioPlayer*audioPlayer;
AVAudioPlayer类也是需要知道音频文件的路径,使用下面代码创建一个AVAudioPlayer实例:

-(id)init

{

self=[superinitWithNibName:@"MediaPlayerViewController"bundle:nil];

if(self){

NSString*musicPath=[[NSBundlemainBundle]pathForResource:@"Music"

ofType:@"mp3"];

if(musicPath){

NSURL*musicURL=[NSURLfileURLWithPath:musicPath];

audioPlayer=[[AVAudioPlayeralloc]initWithContentsOfURL:musicURL

error:nil];

[audioPlayersetDelegate:self];
}

NSString*soundPath=[[NSBundlemainBundle]pathForResource:@"Sound12"

ofType:@"aif"];
我们可以在一个button的点击事件中开始播放这个mp3文件,如:

-(IBAction)playAudioFile:(id)sender

{

if([audioPlayerisPlaying]){//Stopplayingaudioandchangetextofbutton

[audioPlayerstop];

[sendersetTitle:@"PlayAudioFile"

forState:UIControlStateNormal];
}

else{//Startplayingaudioandchangetextofbuttonso//usercantaptostopplayback

[audioPlayerplay];

[sendersetTitle:@"StopAudioFile"

forState:UIControlStateNormal];
}
}
这样运行我们的程序,就可以播放音乐了。

这个类对应的AVAudioPlayerDelegate有两个委托方法。一个是audioPlayerDidFinishPlaying:successfully:
当音频播放完成之后触发。当播放完成之后,可以将播放按钮的文本重新回设置成:PlayAudioFile

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player

successfully:(BOOL)flag

{

[audioButtonsetTitle:@"PlayAudioFile"

forState:UIControlStateNormal];
}
另一个是audioPlayerEndInterruption:,当程序被应用外部打断之后,重新回到应用程序的时候触发。在这里当回到此应用程序的时候,继续播放音乐。

-(void)audioPlayerEndInterruption:(AVAudioPlayer*)player

{

[audioPlayerplay];
}
MediaPlayerframework

播放电影文件:

iOSsdk中可以使用MPMoviePlayerController来播放电影文件。但是在iOS设备上播放电影文件有严格的格式要求,只能播放下面两个格式的电影文件。

•H.264(BaselineProfileLevel3.0)

•MPEG-4Part2video(SimpleProfile)

幸运的是你可以先使用iTunes将文件转换成上面两个格式。

MPMoviePlayerController还可以播放互联网上的视频文件。但是建议你先将视频文件下载到本地,然后播放。如果你不这样做,iOS可能会拒绝播放很大的视频文件。

这个类定义在MediaPlayerframework中。在你的应用程序中,先添加这个引用,然后修改MediaPlayerViewController.h文件。

#import<MediaPlayer/MediaPlayer.h>

@interfaceMediaPlayerViewController:UIViewController<AVAudioPlayerDelegate>

{

MPMoviePlayerController*moviePlayer;
下面我们使用这个类来播放一个.m4v
格式的视频文件。与前面的类似,需要一个url路径。

-(id)init

{

self=[superinitWithNibName:@"MediaPlayerViewController"bundle:nil];

if(self){

NSString*moviePath=[[NSBundlemainBundle]pathForResource:@"Layers"

ofType:@"m4v"];

if(moviePath){

NSURL*movieURL=[NSURLfileURLWithPath:moviePath];

moviePlayer=[[MPMoviePlayerControlleralloc]

initWithContentURL:movieURL];
}
MPMoviePlayerController有一个视图来展示播放器控件,我们在viewDidLoad方法中,将这个播放器展示出来。

-(void)viewDidLoad

{

[[selfview]addSubview:[moviePlayerview]];

floathalfHeight=[[selfview]bounds].size.height/
2.0;

floatwidth=[[selfview]bounds].size.width;

[[moviePlayerview]setFrame:CGRectMake(0,halfHeight,width,halfHeight)];
}
还有一个MPMoviePlayerViewController类,用于全屏播放视频文件,用法和MPMoviePlayerController一样。

MPMoviePlayerViewController*playerViewController=

[[MPMoviePlayerViewControlleralloc]initWithContentURL:movieURL];

[viewControllerpresentMoviePlayerViewControllerAnimated:playerViewController];
我们在听音乐的时候,可以用iphone做其他的事情,这个时候需要播放器在后台也能运行,我们只需要在应用程序中做个简单的设置就行了。

1、在Infopropertylist中加一个
Requiredbackgroundmodes节点,它是一个数组,将第一项设置成设置Appplaysaudio。

2、在播放mp3的代码中加入下面代码:

if(musicPath){

NSURL*musicURL=[NSURLfileURLWithPath:musicPath];

[[AVAudioSessionsharedInstance]

setCategory:AVAudioSessionCategoryPlaybackerror:nil];

audioPlayer=[[AVAudioPlayeralloc]initWithContentsOfURL:musicURL

error:nil];

[audioPlayersetDelegate:self];
}
在后台运行的播放音乐的功能在模拟器中看不出来,只有在真机上看效果。

总结:本文通过例子详细讲解了iOSsdk中用于播放音频文件的类,文章后面有本文的代码提供下载。

代码:http://files.cnblogs.com/zhuqil/MediaPlayer.zip

1.
-(void)applicationDidFinishLaunching:(UIApplication*)application

2.
{

3.
//Initthewindow

4.
window=[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];

5.

6.
//TrytouseCADisplayLinkdirector

7.
//ifitfails(SDK<3.1)usethedefaultdirector

8.

if(![CCDirectorsetDirectorType:kCCDirectorTypeDisplayLink])

9.

[CCDirectorsetDirectorType:kCCDirectorTypeDefault];

10.

11.

CCDirector*director=[CCDirectorsharedDirector];

12.

13.
//InittheViewController

14.

viewController=[[RootViewControlleralloc]initWithNibName:nilbundle:nil];

15.

viewController.wantsFullScreenLayout=YES;

16.

17.
//

18.
//CreatetheEAGLViewmanually

19.
//1.CreateaRGB565format.Alternative:RGBA8

20.
//2.depthformatof0bit.Use16or24bitfor3deffects,likeCCPageTurnTransition

21.
//

22.
//

23.

EAGLView*glView=[EAGLViewviewWithFrame:[windowbounds]

24.
pixelFormat:kEAGLColorFormatRGBA8

25.

depthFormat:0//GL_DEPTH_COMPONENT16_OES

26.
preserveBackbuffer:NO];

27.

28.
//attachtheopenglViewtothedirector

29.

[directorsetOpenGLView:glView];

30.

31.
//ToenableHi-Redmode(iPhone4)

32.
//[directorsetContentScaleFactor:2];

33.

34.
//

35.
//VERYIMPORTANT:

36.
//IftherotationisgoingtobecontrolledbyaUIViewController

37.
//thenthedeviceorientationshouldbe"Portrait".

38.
//

39.
#
if
GAME_AUTOROTATION==kGameAutorotationUIViewController

40.

[directorsetDeviceOrientation:kCCDeviceOrientationPortrait];

41.
#else

42.

[directorsetDeviceOrientation:kCCDeviceOrientationLandscapeLeft];

43.
#endif

44.

45.

[directorsetAnimationInterval:1.0/60];

46.

[directorsetDisplayFPS:NO];

47.

48.
//maketheOpenGLViewachildoftheviewcontroller

49.
//[viewControllersetView:glView];

50.

51.

[viewController.viewaddSubview:glView];

52.

53.
//maketheViewControllerachildofthemainwindow

54.

[windowaddSubview:viewController.view];

55.

56.

[windowmakeKeyAndVisible];

57.

58.

NSURL*url=[NSURLfileURLWithPath:[[NSBundlemainBundle]pathForResource:@"Schwarzweisskratzer"ofType:@"mov"]];

59.

MPMoviePlayerController*moviePlayer=[[MPMoviePlayerControlleralloc]initWithContentURL:url];

60.

61.
//Registertoreceiveanotificationwhenthemoviehasfinishedplaying.

62.

[[NSNotificationCenterdefaultCenter]addObserver:self

63.
selector:@selector(moviePlayBackDidFinish:)

64.
name:MPMoviePlayerPlaybackDidFinishNotification

65.
object:moviePlayer];

66.

67.

if([moviePlayerrespondsToSelector:@selector(setFullscreen:animated:)]){

68.
//Usethenew3.2styleAPI

69.

moviePlayer.controlStyle=MPMovieControlStyleNone;

70.

moviePlayer.shouldAutoplay=YES;

71.

moviePlayer.repeatMode=MPMovieRepeatModeOne;

72.
//[moviePlayersetFullscreen:YESanimated:YES];

73.

CGRectwin=[[UIScreenmainScreen]bounds];

74.
//[moviePlayer.viewsetTransform:CGAffineTransformMakeRotation((float)M_PI_2)];

75.

76.

moviePlayer.view.frame=CGRectMake(0,0,win.size.height,win.size.width);

77.

[viewController.viewaddSubview:moviePlayer.view];

78.

[viewController.viewsendSubviewToBack:moviePlayer.view];

79.
printf("\n\nsoso\n");

80.
}else{

81.
//Usetheold2.0styleAPI

82.

moviePlayer.movieControlMode=MPMovieControlModeHidden;

83.

[moviePlayerplay];

84.
}

85.

86.
//DefaulttextureformatforPNG/BMP/TIFF/JPEG/GIFimages

87.
//ItcanbeRGBA8888,RGBA4444,RGB5_A1,RGB565

88.
//Youcanchangeanytime.

89.

[CCTexture2DsetDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];

90.

91.
//RuntheintroScene

92.

[[CCDirectorsharedDirector]runWithScene:[overlayscene]];


}












NSBundle*appBundle=[NSBundlemainBundle];
NSString*contentURLString=[mainBundlepathForResource:@"Movie"ofType:@"mov"];

if(contentURLString==nil){//Dowhateveryoudoifthefilecan'tbefound}

NSURL*contentURL=[NSURLurlWithString:contentURLString];

mMoviePlayer=[[MPMoviePlayerControlleralloc]initWithContentURL:contentURL];

http://www.techotopia.com/index.php/Video_Playback_from_within_an_iOS_4_iPhone_Application

http://www.iphonedevsdk.com/forum/iphone-sdk-development/18833-need-some-help-using-mpmovieplayer-play-video-file-app.html
http://www.vellios.com/downloads/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: