網頁

2012年8月21日 星期二

avaudioplayer UIProgressView

.m

#import "ViewController.h"


@interface ViewController ()

@end

@implementation ViewController
@synthesize avPlayer;
@synthesize progressBar;

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    
    [progressBar setProgress:0.0]; 
    sound_Timer =[NSTimer scheduledTimerWithTimeInterval:1.0
                                                  target:self 
                                                selector:@selector(updateProgressView) 
                                                userInfo:nil 
                                                 repeats:YES];
    
    
    //btn_sound
    NSString *imgBtnSound = [[NSString alloc] initWithFormat: @"btn_voice.png"];
    
    UIImage *imageBtnSound = [UIImage imageNamed: imgBtnSound];
    UIButton *btnSound = [UIButton buttonWithType: UIButtonTypeCustom];
    btnSound.frame = CGRectMake(0, 0, 87, 88);
    btnSound.center = CGPointMake(220 , 100 );
    [btnSound setBackgroundImage: imageBtnSound forState: UIControlStateNormal]; 
    [btnSound addTarget: self action: @selector(btnPlaySound:) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview: btnSound];
    
}

-(void)updateProgressView {
    
    float totalTime=avPlayer.duration;
    float currentPercent=avPlayer.currentTime / totalTime;
    
    [progressBar setProgress:currentPercent]; 
}

#pragma mark -
#pragma mark Sound custom methods


- (IBAction)btnPlaySound:(id)sender
{
    NSLog(@"Play Sound");
    
    
    NSString *qSound = @"FileName" ; 
    
    [self PlaySound:qSound];
    
}


- (void) PlaySound:(NSString *)qSound
{
    NSURL *url = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:qSound ofType:@"mp3"] isDirectory:NO];
    
    NSError* error = nil;
    
    
    
    avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    avPlayer.delegate  = self;
    if (!url || error) {
        
    }
    avPlayer.volume = 1;
    avPlayer.numberOfLoops = 0;// -1 = repeat forever
    [avPlayer prepareToPlay];
    [avPlayer play];
}

沒有留言:

張貼留言

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