網頁

2012年7月1日 星期日

avaudioplayer uiprogressview countdown


使用 UIPageControl 與 UIScrollView 來實作畫面切換的效果



.h
 
@interface ViewController : UIViewController
{
    
    IBOutlet UIProgressView *progressBar;

    NSTimer *playbackTimer;
    
    AVAudioPlayer *soundPlayer;
    IBOutlet UILabel  *soundPlayerLabel;    
}

@property (nonatomic, retain) IBOutlet UIProgressView *progressBar;


@property (nonatomic, retain) UILabel  *soundPlayerLabel;
@property (nonatomic, strong) AVAudioPlayer *soundPlayer;

.m
 
@synthesize progressBar;

@synthesize soundPlayerLabel;
@synthesize soundPlayer;

- (void)viewWillAppear:(BOOL)animated {
    
    [self playSound];        
}


#pragma mark - PlaySound

- (void) playSound
{

 NSString *fileName = @"1_test_2";
    NSString *filePath =  [[NSBundle mainBundle] pathForResource:fileName ofType:@"mp3"];
 NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: filePath ];
 NSError *error = nil;
 
 AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: &error];
 player.volume = 1;
 player.numberOfLoops = 0;
 [player prepareToPlay];
 self.soundPlayer = player;
    
 if (error)
  NSLog(@"Error");
 
 
    [progressBar setProgress:1.0]; //設為1 表100% rogressBar傳入0~1之間的小數
    playbackTimer=[NSTimer scheduledTimerWithTimeInterval:0.5f
                                                   target:self 
                                                 selector:@selector(updateProgressView) 
                                                 userInfo:nil 
                                                  repeats:YES];
    
    [self.soundPlayer play];
}


#pragma mark - Show Playing Progress


-(void)updateProgressView {
    
    float total=soundPlayer.duration;
    float currentPercent=soundPlayer.currentTime / total;
    
    float countDownPercent = 1-currentPercent;

    [progressBar setProgress:countDownPercent]; 
    
    soundPlayerLabel.text = [NSString stringWithFormat:@"%f", currentPercent];
    
    NSLog(@"soundPlayer.currentTime=%f",soundPlayer.currentTime);
    NSLog(@"total=%f",soundPlayer.duration);  
    NSLog(@"currentPercent=%f",currentPercent);  
    
    if (soundPlayer.isPlaying == 0)
    {
    
        [playbackTimer invalidate];
        [progressBar setProgress:0.0];
    }
    
}


沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。