最近做了一個(gè)播放本地音樂的功能寇壳。音樂的聲音很短暫抽米。在公司的幾個(gè)項(xiàng)目中都有用到舵鳞,記錄下埃唯。
#import <AVFoundation/AVFoundation.h>
static AVAudioPlayer* staticAudioPlayer;
@interface Sound : NSObject
{
AVAudioSession* _audioSession;
}
+(instancetype)sharedInstance;
-(void)play;
-(void)stop;
@end
#import "Sound.h"
@interface Sound ()
@end
@implementation Sound
-(instancetype)init{
if (self = [super init]) {
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
/*
Adding the above line of code made it so my audio would start even if the app was in the background.
*/
NSURL* url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"findPhone" ofType:@"WAV"]];
_audioSession = [AVAudioSession sharedInstance];
[_audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[_audioSession setActive:YES error:nil];
if(!staticAudioPlayer){
staticAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[staticAudioPlayer prepareToPlay];
}
}
return self;
}
+(instancetype)sharedInstance{
static Sound *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
-(void)play{
staticAudioPlayer.volume = 10;
if (!staticAudioPlayer.isPlaying) {
[staticAudioPlayer play];
}
}
-(void)stop{
staticAudioPlayer.currentTime = 0;
[staticAudioPlayer stop];
}
@end