iOS 音訊開發AVAudioPlayer的使用,音效播放AudioServicesPlaySystemSound使用
音訊開發AVAudioPlayer的使用
AVAudioPlayer是iOS系統自帶的可以播放本地mp3檔案的一個類,(注意:只能播放本地)
參考:http://www.jianshu.com/p/589999e53461
1,先匯入庫AVFoundation/AVFoundation.h 並進行代理AVAudioPlayerDelegate
2,把將要播放的mp3檔案匯入工程
下面貼程式碼:
定義需要用到的全域性變數
@property (nonatomic , strong) AVAudioPlayer *player;
@property (weak, nonatomic) IBOutlet UIProgressView *Progress;
@property (weak, nonatomic) IBOutlet UILabel *CurrentTime;
@property (weak, nonatomic) IBOutlet UILabel *countTime;
@property (nonatomic,strong)NSArray *sourceArray;//歌曲陣列
@property (nonatomic,copy)NSString *currentsong;
@property (nonatomic,strong)NSTimer *timer;//定時器
-(void)viewDidLoad {
[super viewDidLoad];
_sourceArray = @[@"muise",@"music2"]; NSUserDefaults *usedefault = [NSUserDefaults standardUserDefaults]; NSString *songStr = [usedefault objectForKey:@"current_song"]; if (songStr.length == 0) { songStr = _sourceArray[0]; [usedefault setObject:@"0" forKey:@"current_song"]; [usedefault synchronize]; } NSString *str = _sourceArray[[songStr intValue]]; [self PlayMusicWith:str]; _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES]; [_timer setFireDate:[NSDate distantFuture]]; // Do any additional setup after loading the view, typically from a nib.
}
//暫停按鈕
-(IBAction)Stop:(id)sender {
[self.player stop];
[_timer setFireDate:[NSDate distantFuture]];
}
//下一曲按鈕
-(IBAction)Next:(id)sender {
[self NextSong];
}
//上一曲按鈕
-(IBAction)Previous:(id)sender {
NSUserDefaults *usedefault = [NSUserDefaults standardUserDefaults]; NSString *songStr = [usedefault objectForKey:@"current_song"]; int a = [songStr intValue]-1; if (a <0) { a = (int)_sourceArray.count -1; [usedefault setObject:[NSString stringWithFormat:@"%d",a] forKey:@"current_song"]; [usedefault synchronize]; }else{ [usedefault setObject:[NSString stringWithFormat:@"%d",a]forKey:@"current_song"]; [usedefault synchronize]; } NSLog(@"上一曲a==== %d",a); [self PlayMusicWith:_sourceArray[a]];
}
//初始化播放器並播放
-(void)PlayMusicWith:(NSString *)songName{
NSURL *url = [[NSBundle mainBundle] URLForResource:songName withExtension:@"mp3"];
self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
self.player.delegate = self;
NSInteger countTime = self.player.duration;
_countTime.text = [NSString stringWithFormat:@"%d:%d",(int)countTime/60,(int)countTime%60];//歌曲總長度
[self.player play];
//設定鎖屏仍能繼續播放
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
}
//代理方法
//播放結束自動切換為下一首
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
NSLog(@”播放結束”);
// 切換下一首
[self NextSong];
}
//中斷
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
NSLog(@”一般這個方法中會暫停音訊”);
// [player stop];
}
// 中斷結束的時候會呼叫這個方法
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags {
// 一般在這個方法中繼續播放音訊
[player play];
NSLog(@”繼續播放”);
}
// 解碼錯誤的時候會呼叫這個方法
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer )player error:(NSError )error {
NSLog(@”檔案出錯”);
}
//下一首
-(void)NextSong{
NSUserDefaults *usedefault = [NSUserDefaults standardUserDefaults];
NSString *songStr = [usedefault objectForKey:@"current_song"];
int a = [songStr intValue]+1;
if (a >=_sourceArray.count) {
a = 0;
[usedefault setObject:@"0" forKey:@"current_song"];
[usedefault synchronize];
}else{
[usedefault setObject:[NSString stringWithFormat:@"%d",a]forKey:@"current_song"];
[usedefault synchronize];
}
NSLog(@"下一曲a==== %d",a);
[self PlayMusicWith:_sourceArray[a]];
}
-(void)timerAction{
NSUInteger a = self.player.currentTime;
// _CurrentTime.text = [[NSString stringWithFormat:@”%.2f”,a/60.00,self.player.currentTime] stringByReplacingOccurrencesOfString:@”.” withString:@”:”];
NSLog(@"kkkk %ld %f",a,self.player.currentTime);
int b = a%60;
if (b<10) {
}
int c = (int)a/60;
_CurrentTime.text =[NSString stringWithFormat:@"%d:%d",c,b];// [[NSString stringWithFormat:@"%",a/60.00] stringByReplacingOccurrencesOfString:@"." withString:@":"];
_Progress.progress = _player.currentTime/_player.duration;
}
音效播放AudioServicesPlaySystemSound使用
- (IBAction)Playmusic:(id)sender {
NSLog(@"音樂播放");
[self.player play];
[_timer setFireDate:[NSDate distantPast]];
NSLog(@"hhhh %f",self.player.currentTime);
}
-(void)playSoundEffect:(NSString*)name {
//獲取檔案的路徑
NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:name ofType:nil];
NSURL *fileUrl = [NSURL fileURLWithPath:audioFilePath];
//1.獲取系統聲音ID
SystemSoundID soundID = 0;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
//2.如何播放完之後需要執行某些操作,可以呼叫下面方法
AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL,soundCompleteCallBack, NULL);
//3.播放音訊
AudioServicesPlaySystemSound(soundID);
// 這個方法直接監聽播放完成回撥,方便了很多
AudioServicesPlaySystemSoundWithCompletion(soundID, ^{
NSLog(@"播放完成回撥");
});
AudioServicesPlayAlertSound(soundID); // 播放並且震動
}
void soundCompleteCallBack(SystemSoundID soundID,void* clientDate) {
NSLog(@"播放完成");
}