iOS AVAudioPlayer播放音频文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25639809/article/details/89329779

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

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

AVAudioPlayerManager文件

#import <Foundation/Foundation.h>

@interface AVAudioPlayerManager : NSObject

+ (instancetype)shared;

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

- (void)shock;

@end
#import "AVAudioPlayerManager.h"
#import <AVFoundation/AVFoundation.h>

@interface AVAudioPlayerManager() <AVAudioPlayerDelegate>

@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

猜你喜欢

转载自blog.csdn.net/qq_25639809/article/details/89329779