iOS之AVAudioPlayer 音頻播放

一,AVAudioPlayer本地音頻播放
  • 使用AVAudioPlayer,需要導入AVFoundation.framework;
  • 支持的音頻格式包括:AAC、ALAC、IMA4、linear、MP3;
  • AVAudioPlayer支持播放單個聲音的能力,但并不支持流式播放,所以必須是緩沖完才能播放;
#import <AVFoundation/AVFoundation.h>
@interface AudioToolManager()<AVAudioPlayerDelegate>
/**
 播放器
 */
@property (nonatomic, strong) AVAudioPlayer *player;
@end
@implementation AudioToolManager
//初始化播放器
-(AVAudioPlayer*)player{
    if (!_player) {
        NSError *err;
        NSURL *url = [[NSBundle mainBundle] URLForResource:@“xxx” withExtension:@"mp3"];//wav
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];
        _player.delegate = self;
        //獲取系統(tǒng)的聲音
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        CGFloat currentVol = audioSession.outputVolume; 
        //設置播放器聲音
        _player.volume = currentVol;
        //設置播放速率
        _player.rate = 1.0;
        //設置播放次數(shù),負數(shù)代表無限循環(huán)
//        _player.numberOfLoops = 1;
        //預加載資源
        [_player prepareToPlay];
    }
    return _player;
}

//開始播放
-(void)startPlay{
    if ([self.player isPlaying]) {
        [self.player stop];
    }
    [self.player play];
}

//停止播放
-(void)stopPlay{
    [self.player stop];
}

//暫停播放
-(void)pausePLay{
   [self.player pause];
}

#pragma mark -- delegate
// 音頻播放完成時
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@“播放完成”);
}

// 音頻播放出錯時
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error{
    NSLog(@“播放出錯了”);
}
@end
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容