頭文件:oop
#import <AVFoundation/AVFoundation.h>atom
代理:url
AVAudioPlayerDelegatespa
單例頭文件:代理
#import "Singleton.h"code
@interface music : NSObjectorm
@property (nonatomic, copy) NSString *nameyinyue;對象
@property (nonatomic, copy) NSString *nameyinxiao;blog
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;事件
+ (music *) sharedInstance;
@end
@property(strong,nonatomic) music *music_t;
_music_t=[music sharedInstance];
#pragma mark -懶加載 -(AVAudioPlayer *)audioPlayer { if (!_music_t.audioPlayer ) { // 0. 設置後臺音頻會話 [self setBackGroundPlay]; // 1. 獲取資源URL NSURL *url = [[NSBundle mainBundle] URLForResource:@"櫻花櫻花想見你.mp3" withExtension:nil]; // 2. 根據資源URL, 建立 AVAudioPlayer 對象 _music_t.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; // 2.1 設置容許倍速播放 self.audioPlayer.enableRate = YES; // 3. 準備播放 [_music_t.audioPlayer prepareToPlay]; // 4. 設置代理, 監聽播放事件 _music_t.audioPlayer.delegate = self; } return _music_t.audioPlayer; } - (void)setBackGroundPlay { // 1. 設置會話模式 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; ; // 2. 激活會話 [[AVAudioSession sharedInstance] setActive:YES error:nil]; }
//點擊播放或者暫停 -(void)btn1ButtonAction:(UIButton *)btn { if ([_music_t.nameyinxiao isEqualToString:@"暫停音效"]) { [self initWithYinxiao]; } if ([_music_t.nameyinyue isEqualToString:@"播放音樂"]) { [self.audioPlayer play]; NSLog(@"+++++++++++++++"); self.audioPlayer.numberOfLoops = -1; _music_t.nameyinyue=@"暫停音樂"; } else{ [self.audioPlayer pause]; NSLog(@"--------------"); _music_t.nameyinyue=@"播放音樂"; } [_btnYinyue setImage:[UIImage imageNamed:_music_t.nameyinyue] forState:UIControlStateNormal]; }