ios中播放本地音乐文件

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容