標籤:
今天記錄一下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);
iOS播放器 - AVAudioPlayer