iOS播放器 - AVAudioPlayer

今天记录一下AVAudioPlayer,这个播放器类苹果提供了一些代理方法,主要用来播放本地音频。

其实也可以用来播放网络音频,只不过是将整个网络文件下载下来而已,在实际开发中会比较耗费流量不做推荐。

下面是相关代码:

#import "ViewController.h"

//引入框架

#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

<AVAudioPlayerDelegate>

//设置全局对象,否则将会出现没有声音出现的情况

@property (nonatomic,strong) AVAudioPlayer *audioPlayer;

@property (nonatomic,strong) NSTimer *timer;

@property (nonatomic,strong) NSArray *mp3Array;

@property (nonatomic) NSInteger currentMp3;

@property (nonatomic,strong) NSArray *lrcArray;

@property (nonatomic,strong) CYParserLrc *parser;

@property (nonatomic)NSInteger currentRow;

@end

@implementation ViewController

-(void)initWithMp3Path:(NSString *)mp3Path lrcPath:(NSString *)lrcPath

{

    //initWithContentsOfURL 路径(本地)

    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:mp3Path] error:nil];

    //准备播放

    [self.audioPlayer prepareToPlay];

    //设置声音

    self.audioPlayer.volume = 0.5f;

  //设置代理

    self.audioPlayer.delegate = self;

     //设置进度条最大值

     //duration  当前音乐的总时间

    self.song.maximumValue = self.audioPlayer.duration;

    //解析歌词

    [self.parser parserLrc:lrcPath];

    //下一曲 刷新tableView

    [self.tableView reloadData];

    self.timer = [NSTimer scheduledTimerWithTimeInterval:.1f target:self selector:@selector(timeChange) userInfo:nil repeats:YES];

   

}

#pragma 代理方法

/* audioPlayerDidFinishPlaying:successfully: is called when a sound has finished playing. This method is NOT called if the player is stopped due to an interruption. */

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;

 

/* if an error occurs while decoding it will be reported to the delegate. */

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error;

 

#if TARGET_OS_IPHONE

 

/* AVAudioPlayer INTERRUPTION NOTIFICATIONS ARE DEPRECATED - Use AVAudioSession instead. */

 

/* audioPlayerBeginInterruption: is called when the audio session has been interrupted while the player was playing. The player will have been paused. */

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player NS_DEPRECATED_IOS(2_2, 8_0);

 

/* audioPlayerEndInterruption:withOptions: is called when the audio session interruption has ended and this player had been interrupted while playing. */

/* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags NS_DEPRECATED_IOS(6_0, 8_0);

 

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withFlags:(NSUInteger)flags NS_DEPRECATED_IOS(4_0, 6_0);

 

/* audioPlayerEndInterruption: is called when the preferred method, audioPlayerEndInterruption:withFlags:, is not implemented. */

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player NS_DEPRECATED_IOS(2_2, 6_0);

 

posted @ 2016-06-15 14:52  SunnyOMGi  阅读(624)  评论(0编辑  收藏  举报