ios中播放本地音乐文件

最近做了一个播放本地音乐的功能。音乐的声音很短暂。在公司的几个项目中都有用到,记录下。
#import 

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

你可能感兴趣的:(ios中播放本地音乐文件)