xcode添加音效:http://www.cnblogs.com/jiayongqiang/p/5625886.html
背景音樂:
ios播放音樂時會用到一個叫做AVAudioPlayer的類,這個類用於播放手機本地的音樂文件。需要注意的是
(1)該類(AVAudioPlayer)只能用於播放本地音頻。
(2)時間比較短的(音效)使用AudioServicesCreateSystemSoundID來創建,而本地時間較長(音樂)使用AVAudioPlayer類。
步驟:
1.導入導入AVFoundation框架。
2.導入頭文件#import <AVFoundation/AVFoundation.h>
3.導入背景音樂.
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 = -1; //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 崩潰問題:
