SceneKit 播放本地音频

最近在研究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];

}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值