iOS AVAudioPlayer播放音频文件

使用AVAudioPlayer播放本地的work.mp3文件,只需要调用下面一行代码:

[AVAudioPlayerManager.shared playLocalFile:@"work" ofType:@"mp3"];

AVAudioPlayerManager文件

#import 

@interface AVAudioPlayerManager : NSObject

+ (instancetype)shared;

- (void)playLocalFile:(NSString *)name ofType:(NSString *)type;

- (void)shock;

@end
#import "AVAudioPlayerManager.h"
#import 

@interface AVAudioPlayerManager() 

@property (nonatomic, strong) AVAudioPlayer *player;

@end

@implementation AVAudioPlayerManager

+ (id)shared {
    static  dispatch_once_t once;
    static   id instance;
    dispatch_once(&once, ^{
        instance = [self new];
    });
    return instance;
}

- (void)playLocalFile:(NSString *)name ofType:(NSString *)type {
    if (self.player.isPlaying) {
        [self.player pause];
    }
    /* 获取本地文件 */
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *urlString = [bundle pathForResource:name ofType:type];
    NSURL *url = [[NSURL alloc] initFileURLWithPath:urlString];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url fileTypeHint:nil error:nil];
    self.player.delegate = self;
    [self.player prepareToPlay];
    [self.player play];
    [self shock];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
}

- (void)shock {
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
//    AudioServicesPlaySystemSound(1519);
}

@end

你可能感兴趣的:(IOS)