iOS 音频播放

作者: _Waiting_ | 来源:发表于2022-08-17 10:58 被阅读0次
    //
    //  HanAudioPlayer.h
    //  HT-AVAudioPlayer
    //
    //  Created by han on 2022/8/2.
    //
    
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    #import <AVFoundation/AVFoundation.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    
    @class HanAudioPlayer;
    
    @protocol HanAudioPlayerDelegate <NSObject>
    @optional
    ///播放完成
    - (void)audioPlayerDidFinishPlaying:(HanAudioPlayer *)player successfully:(BOOL)flag;
    ///解析音乐出错
    - (void)audioPlayerDecodeErrorDidOccur:(HanAudioPlayer *)player error:(NSError * __nullable)error;
    
    @end
    
    
    @interface HanAudioPlayer : NSObject
    
    @property (readonly,nonatomic, strong) AVAudioPlayer *audioPlayer;
    
    @property (nonatomic, weak) id<HanAudioPlayerDelegate> delegate;
    
    /// 初始化 默认循环播放 最大音量一半播放
    /// @param url 音乐地址
    - (instancetype)initAudioPlayerWithURL:(NSString *)url;
    
    /// 播放音乐
    - (void)playRadio;
    
    /// 播放音乐
    /// @param url 音乐地址
    - (void)playRadioWithURL:(NSString *)url;
    
    /// 播放音乐
    /// @param time 从什么位置播放
    - (void)playRadioAtTime:(NSTimeInterval)time;
    
    /// 暂停播放
    - (void)pauseRadio;
    
    /// 停止播放
    - (void)stopRadio;
    
    /// 播放次数
    /// @param number 次数 -1循环播放
    - (void)numberOfLoops:(NSInteger)number;
    
    /// 播放音量
    /// @param volume 音量 0-1
    - (void)setVolume:(CGFloat)volume;
    
    
    /// 设置外放
    /// @param isSpeaker 是否外放
    - (void)setSpeaker:(BOOL)isSpeaker;
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    
    //
    //  HanAudioPlayer.m
    //  HT-AVAudioPlayer
    //
    //  Created by han on 2022/8/2.
    //
    
    #import "HanAudioPlayer.h"
    #import "HanAudioPlayer+FileManage.h"
    
    @interface HanAudioPlayer ()<AVAudioPlayerDelegate>
    
    @property (nonatomic, strong) AVAudioPlayer *audioPlayer;
    
    @end
    
    @implementation HanAudioPlayer
    
    - (instancetype)initAudioPlayerWithURL:(NSString *)url{
        if (self = [super init]) {
            [self loadAudioPlayerWithURL:url];
        }
        return self;
    }
    
    #pragma mark - public
    - (void)playRadio{
        [self.audioPlayer play];
    }
    
    - (void)playRadioAtTime:(NSTimeInterval)time{
        [self.audioPlayer playAtTime:time];
    }
    
    - (void)numberOfLoops:(NSInteger)number{
        self.audioPlayer.numberOfLoops = number;
    }
    
    - (void)pauseRadio{
        [self.audioPlayer pause];
    }
    
    - (void)stopRadio{
        [self.audioPlayer stop];
        self.audioPlayer.currentTime = 0;
    }
    
    - (void)playRadioWithURL:(NSString *)url{
        [self loadAudioPlayerWithURL:url];
        [self playRadio];
    }
    
    - (void)setVolume:(CGFloat)volume{
        self.audioPlayer.volume = volume;
    }
    - (void)setSpeaker:(BOOL)isSpeaker{
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if (isSpeaker) {
            [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        }else{
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        }
        [audioSession setActive:YES error:nil];
    }
    #pragma mark - private
    - (void)loadAudioPlayerWithURL:(NSString *)url{
        if (url.length != 0) {
            if (self.audioPlayer) {
                [self stopRadio];
                self.audioPlayer = nil;
            }
            NSData *data = [NSData data];
            BOOL isHave = [HanAudioPlayer fileIsExists:[HanAudioPlayer getAudioPath]];
            if (isHave) {
                data = [NSData dataWithContentsOfFile:[HanAudioPlayer getAudioPath]];
            }else{
                if ([url hasPrefix:@"https://"] || [url hasPrefix:@"http://"]) {
                    NSURL *URL = [[NSURL alloc] initWithString:url];
                    if (URL) {
                        data = [NSData dataWithContentsOfURL:URL];
                        __weak typeof(self) this = self;
                        [this saveAudio:data];
                        [this saveFileKey:url];
                    }
                }else{
                    if (![self fileIsExists:url]) {
                        return;
                    }
                    data = [NSData dataWithContentsOfFile:url];
                }
            }
            if (data.length > 0) {
                NSError *error;
                self.audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
                self.audioPlayer.numberOfLoops = -1;
                self.audioPlayer.volume = 0.5;
                self.audioPlayer.delegate = self;
            }
            
        }
    }
    
    #pragma mark - AVAudioPlayerDelegate
    ///播放完成
    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
        if (self.delegate && [self.delegate respondsToSelector:@selector(audioPlayerDidFinishPlaying:successfully:)]) {
            [self.delegate audioPlayerDidFinishPlaying:self successfully:flag];
        }
    }
    ///解析音乐出错
    - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error{
        if (self.delegate && [self.delegate respondsToSelector:@selector(audioPlayerDecodeErrorDidOccur:error:)]) {
            [self.delegate audioPlayerDecodeErrorDidOccur:self error:error];
        }
    }
    
    @end
    
    

    对音乐做本地处理

    //
    //  HanAudioPlayer+FileManage.h
    //  HT-AVAudioPlayer
    //
    //  Created by han on 2022/8/2.
    //
    
    #import "HanAudioPlayer.h"
    
    NS_ASSUME_NONNULL_BEGIN
    
    
    @interface HanAudioPlayer (FileManage)
    
    /// 文件是否存在
    /// @param path 地址
    - (BOOL)fileIsExists:(NSString *)path;
    + (BOOL)fileIsExists:(NSString *)path;
    
    /// 保存fileKey
    /// @param fileKey fileKey
    -(void)saveFileKey:(NSString *)fileKey;
    
    /// 保存音乐
    /// @param audioData 音乐
    - (void)saveAudio:(NSData *)audioData;
    
    ///Key路径
    -(NSString *)getKeyPath;
    +(NSString *)getKeyPath;
    
    ///Audio路径
    -(NSString *)getAudioPath;
    +(NSString *)getAudioPath;
    @end
    
    NS_ASSUME_NONNULL_END
    
    
    //
    //  HanAudioPlayer+FileManage.m
    //  HT-AVAudioPlayer
    //
    //  Created by han on 2022/8/2.
    //
    
    #import "HanAudioPlayer+FileManage.h"
    
    @implementation HanAudioPlayer (FileManage)
    - (BOOL)fileIsExists:(NSString *)path{
        NSFileManager* fileManager = [NSFileManager defaultManager];
        BOOL isDirExist = [fileManager fileExistsAtPath:path
                                                isDirectory:nil];
        return isDirExist;
    }
    + (BOOL)fileIsExists:(NSString *)path{
        return [[[self alloc] init] fileIsExists:path];
    }
    -(BOOL)createDirectory:(NSString*)audioPath
    {
        NSFileManager* fileManager = [NSFileManager defaultManager];
        
        BOOL isDirExist = [fileManager fileExistsAtPath:audioPath
                                            isDirectory:nil];
        if(!isDirExist)
        {
            BOOL bCreateDir = [fileManager createDirectoryAtPath:audioPath
                                     withIntermediateDirectories:YES
                                                      attributes:nil
                                                           error:nil];
            
            if(!bCreateDir){
                
                NSLog(@"创建文件夹失败");
                return NO;
                
            }
        }
        return YES;
    }
    -(void)saveFileKey:(NSString *)fileKey{
        if (fileKey) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSData* stringData  = [[NSString stringWithFormat:@"%@",fileKey] dataUsingEncoding:NSUTF8StringEncoding];
                [stringData writeToFile:[self getKeyPath] atomically:YES];
            });
            
        }
    }
    -(void)saveAudio:(NSData *)audioData{
        if (audioData) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [audioData writeToFile:[self getAudioPath] atomically:YES];
            });
        }
    }
    -(NSData *)getAudioData{
        NSString *path = [self getAudioPath];
        NSData *data = [NSData dataWithContentsOfFile:path];
        return data;
    }
    ///Key路径
    -(NSString *)getKeyPath{
        NSArray *paths  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        //获取文件路径
        NSString *theFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"/cs/key.txt"];
        
        return theFilePath;
    }
    +(NSString *)getKeyPath{
        return [[[self alloc] init] getKeyPath];
    }
    ///Audio路径
    -(NSString *)getAudioPath{
        NSArray *paths  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        //获取文件路径
        NSString *theFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"/cs/waiting.wav"];
        
        return theFilePath;
    }
    +(NSString *)getAudioPath{
        return [[[self alloc] init] getAudioPath];
    }
    ///CustomerService文件夹路径
    -(NSString *)getCSPath{
        NSArray *paths  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        //获取文件路径
        NSString *theFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"/cs/waiting.wav"];
        
        return theFilePath;
    }
    -(void)writeTextToPath:(NSString *)path withContent:(NSString *)content {
        if (content.length == 0) {
            return;
        }
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            @synchronized (self) {
                NSString *theFilePath = path;
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if(![fileManager fileExistsAtPath:theFilePath]){
                    NSString *str = @"";
                    [str writeToFile:theFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
                }
                NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:theFilePath];
                [fileHandle seekToEndOfFile];
                NSData* stringData  = [[NSString stringWithFormat:@"%@",content] dataUsingEncoding:NSUTF8StringEncoding];
                [fileHandle writeData:stringData];
                [fileHandle closeFile];
            }
        });
    }
    ///清空文件
    -(void)clearFile{
        //获取文件路径
        NSString *theFilePath = [self getCSPath];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *error;
        [fileManager removeItemAtPath:theFilePath error:&error];
    }
    @end
    
    

    相关文章

      网友评论

        本文标题:iOS 音频播放

        本文链接:https://www.haomeiwen.com/subject/pgejgrtx.html