xcode添加背景音乐/音效

时间:2022-05-26 20:32:18

xcode添加音效:http://www.cnblogs.com/jiayongqiang/p/5625886.html

背景音乐:

ios播放音乐时会用到一个叫做AVAudioPlayer的类,这个类用于播放手机本地的音乐文件。需要注意的是

  (1)该类(AVAudioPlayer)只能用于播放本地音频。

  (2)时间比较短的(音效)使用AudioServicesCreateSystemSoundID来创建,而本地时间较长(音乐)使用AVAudioPlayer类。

步骤:

1.导入导入AVFoundation框架。

    xcode添加背景音乐/音效

2.导入头文件#import <AVFoundation/AVFoundation.h>

3.导入背景音乐.

      xcode添加背景音乐/音效

4.书写代码:

    

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h> @interface ViewController ()
@property (nonatomic,strong) AVAudioPlayer *player;
@end @implementation ViewController
-(AVAudioPlayer *)player{
if (!_player) {
//1.创建音乐路径
NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"五环之歌" ofType:@"mp3"];
NSURL *musicURL = [[NSURL alloc]initFileURLWithPath:musicFilePath]; //2.创建播放器
_player = [[AVAudioPlayer alloc]initWithContentsOfURL:musicURL error:nil]; }
return _player;
}
- (void)viewDidLoad {
[super viewDidLoad];
//3.预播放
[self.player prepareToPlay];
//4.设置播放次数.-1为循环播放
self.player.numberOfLoops = -;
//5.开始播放
[self.player play]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//6.暂停播放, dispatch_after 延迟加载方法. 这里设置为2s,也可以设置其他的延迟秒数
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2* NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
// [self.player stop];
// }); [self.player stop]; }

AVAudioPlayer 崩溃问题:

    xcode添加背景音乐/音效