最近在研究SceneKit,写了一的演示来播放音频,记录下来,看看以后还有更好的方式没有。
新建一个继承于SCNNode的类。导入框架
#import <AVFoundation / AVFoundation.h>
这个是播放本地音乐的。创建一个SCNPlan,我用来显示图标,且设置材质球给计划
- (void)initialize {
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:_musicPathString] error:&error];
_audioPlayer.delegate = self;
_audioPlayer.numberOfLoops = 0;
SCNMaterial *material = [SCNMaterial material];
material.diffuse.contents = _audioPlayer;
SCNPlane *plan = [SCNPlane planeWithWidth:2 height:2];
[plan insertMaterial:material atIndex:1];
plan.firstMaterial.diffuse.contents = [UIImage imageNamed:@"music"];
self.geometry = plan;
if (_audioPlayer) {
[_audioPlayer prepareToPlay];
}
}
设置音频播放,暂停,停止,以及节点的旋转动画
- (void)play {
[_audioPlayer play];
[self runAction:[SCNAction repeatActionForever:self.rotateAction] forKey:@"rotateKey"];
}
- (void)pause {
[_audioPlayer pause];
[self removeActionForKey:@"rotateKey"];
}
- (void)stop {
[_audioPlayer stop];
}
- (BOOL)isPlaying {
return _audioPlayer.isPlaying;
}
- (SCNAction *)rotateAction {
if (!_rotateAction) {
_rotateAction = [SCNAction rotateByX:0 y:0 z:1 duration:2];
}
return _rotateAction;
}
调用方法
- (void)addMusic {
NSString *videoPathString = [[NSBundle mainBundle] pathForResource:@"今生今世遥不可及" ofType:@"mp3"];
WTMusicPlayNode *musciNode = [[WTMusicPlayNode alloc] initWithMusicPathString:videoPathString];
[musciNode play];
[_scnView.scene.rootNode addChildNode:musciNode];
}