1. 程式人生 > >AVAudioPlayer播放音訊檔案

AVAudioPlayer播放音訊檔案

在viewdidload 載入 [self didLoadAudioPlayer];
- (void) didLoadAudioPlayer{
    NSString * musicFilePath = @"/Users/Shared/test.mp3";      //建立音樂檔案路徑    
    NSURL * musicURL= [[NSURL alloc] initFileURLWithPath:musicFilePath];  
    
    AVAudioPlayer * thePlayer  = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil]; //建立播放器
    
    self.player = thePlayer;    //賦值給自己定義的類變數
    
    [musicURL release];
    [thePlayer release];
    
    
    [player setVolume:1];   //設定音量大小
    player.numberOfLoops = -1;//設定音樂播放次數  -1為一直迴圈    
       
     //用NSTimer來監控音訊播放進度
     timer = [NSTimer scheduledTimerWithTimeInterval:0.1 
                                              target:self
                                            selector:@selector(playProgress)
                                            userInfo:nil repeats:YES];
    
}
//播放進度條
 - (void)playProgress {
     
    //通過音訊播放時長的百分比,給progressview進行賦值;
     musicProcess.progress = player.currentTime/player.duration;
     
}
//播放完成時呼叫的方法 需要設定代理才可以呼叫
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    
     [timer invalidate]; //NSTimer暫停   invalidate  使...無效;
    
 }
- (IBAction)musicPlay:(id)sender {
    [player play];
    AudioSessionSetActive(true);
}
- (IBAction)musicStop:(id)sender {
    [player pause];
    AudioSessionSetActive(false);
}