Cocos2d-播放音乐&&视频[转载]

转自:http://www.himigame.com/iphone-cocos2d/482.html 感谢HIMI分享;
   //加载背景音乐&&游戏中的音效
[[SimpleAudioEngine sharedEngine] preloadBackgroundMusic:@"powerup.caf"];
[[SimpleAudioEngine sharedEngine] preloadEffect:@"shake.caf"];

//播放背景音乐
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"powerup.caf"];
//循环播放背景音乐
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"powerup.caf" loop:YES];
//暂停背景音乐
[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];
//继续播放背景音乐
[[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];
//停止背景音乐
[[SimpleAudioEngine sharedEngine] stopBackgroundMusic];
//播放游戏音效;
[[SimpleAudioEngine sharedEngine] playEffect:@"shake.caf"];

1.在播放背景音乐与音效之前都要提前加载,防止加载消耗时间发生与游戏不同步;

2.播放背景音乐的时候,即使切换背景音乐也不用管,coco是d会暂停之前的播放最新的;

3.别忘记导入#import “SimpleAudioEngine.h



关于在cocos2d中进行视频的播放,我想很多童鞋为之烦恼。。。原因是cocos2d本身的引擎中并没有封装,所以很多童鞋最终被迫选用ios sdk中的MPMoviePlayerController;但是Himi研究过后发现,虽然cocos2d本身引擎并没有封装视频播放,但是cocos2d有一个扩展库“ Cocos2D-iPhone-Extensions”,Cocos2D-iPhone-Extensions中除了支持cocos2d的视频播放还附带其他的支持,例如菜单、滚动layer等等,那么本章就不多介绍了,主要介绍Cocos2D-iPhone-Extensions带给我们的视频播放扩展类:CCVideoPlayer 【Cocos2D-iPhone-Extensions 类库本章最后放出下载连接!】

                 大致介绍后,下面我们来具体介绍如何利用扩展包在cocos2d项目中进行视频播放!

步骤一: 将下载后的Cocos2D-iPhone-Extensions包解压,然后找到Extensions/CCVideoPlayer文件夹,将CCVideoPlayer下的iOS包与“CCVideoPlayer.h”和”CCVideoPlayer.m”导入我们的项目中;如下图:

步骤二:添加ios sdk中的MediaPlayer框架(真机调试程序可略过此步)

          点击项目,然后选择-targets-Build Phases页面,然后展开“Link Binary With Libraries”,最后点击“+”号将 “MediaPlayer.framework”添加即可;如下图:

  步骤三:修改需要播放视频的layer类,这里拿HelloWorldLayer举例

           在”HelloWorldLayer.h”类中,导入#import “CCVideoPlayer.h”,然后让HelloWorldLayer使用协议<CCVideoPlayerDelegate>;

在“HelloWorldLayer.m”类中,在init方法中添加初始化vedeoPlayer的方法:

1
[CCVideoPlayer setDelegate: self];

然后在“HelloWorldLayer.m”类中重写如下函数:

- (void) moviePlaybackFinished
{
CCLOG(@"moviePlaybackFinished");
}

- (void) movieStartsPlaying
{
CCLOG(@"movieStartsPlaying");
}

#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
// Updates orientation of CCVideoPlayer. Called from SharedSources/RootViewController.m
- (void) updateOrientationWithOrientation: (UIDeviceOrientation) newOrientation

{
CCLOG(@"updateOrientationWithOrientation");
[CCVideoPlayer updateOrientationWithOrientation:newOrientation ];
}
#endif

到此添加的就完成了,但是如果此时你编译会发现有一处错误,就是在扩展库的”CCVideoPlayer.m”类中还要将下面这句注视掉:
1
#import "CCVideoPlayerImplMac.h"

因为扩展库也支持mac的视频播放,我们做ios肯定不需的,直接屏蔽删除即可;

OK,下面给出简单的两个常用的播放视频的方法:

[CCVideoPlayer playMovieWithFile: @"himi.mp4"];//播放视频
[CCVideoPlayer setNoSkip: YES];//视频是否可以跳过

好啦,由于cocos2d中直接播放视频的文章极少,绝大部分童鞋虽然大概知道这个扩展库但是不知道具体如何使用,所以今天Himi放出这篇博文,希望大家能及时看到;

posted @ 2012-03-19 22:15  moon_7  阅读(279)  评论(0编辑  收藏  举报