美文网首页
iOS 音频文件播放

iOS 音频文件播放

作者: zxb有缘 | 来源:发表于2021-10-11 11:05 被阅读0次

    直接可以使用

    ------------------------------------ .h文件 ----------------------------------

    import <Foundation/Foundation.h>

    import <AVFoundation/AVFoundation.h>

    NS_ASSUME_NONNULL_BEGIN

    @interface CEMAVAudioPlayer : NSObject
    {
    AVAudioSession* _audioSession;
    }

    //第一种
    @property(strong,nonatomic) AVPlayer *player;

    +(instancetype)sharedInstance;

    -(void)play;

    -(void)stop;

    @end

    NS_ASSUME_NONNULL_END

    ------------------------------------ .m文件 ----------------------------------

    import "CEMAVAudioPlayer.h"

    @implementation CEMAVAudioPlayer

    -(instancetype)init{
    if (self = [super init]) {
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

        NSURL* url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Findphone" ofType:@"mp3"]];
        
        /* 第一种
         if (_player == nil) {
         _player = [[AVPlayer alloc] init];
         _player.volume = 1.0; // 默认最大音量
         }
         // 创建要播放的资源
         AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:url];
         // 播放当前资源
         [self.player replaceCurrentItemWithPlayerItem:playerItem];
         */
        
        //第二种
        _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;
    

    }

    static AVAudioPlayer* staticAudioPlayer;
    +(instancetype)sharedInstance{
    static CEMAVAudioPlayer *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];
    }

    //第一种
    //[self.player play];
    

    }

    -(void)stop{
    staticAudioPlayer.currentTime = 0;
    [staticAudioPlayer stop];

    //第一种
    //[self.player pause];
    

    }

    @end

    相关文章

      网友评论

          本文标题:iOS 音频文件播放

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