头文件:
#import <AVFoundation/AVFoundation.h>
代理:
AVAudioPlayerDelegate
单例头文件:
#import "Singleton.h"
@interface music : NSObject
@property (nonatomic, copy) NSString *nameyinyue;
@property (nonatomic, copy) NSString *nameyinxiao;
@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]; }