AVAudioPlayer的使用

AVAudioPlayer的使用

From: http://hi.baidu.com/loveipon/item/367747a64e1cf639a8cfb7c8

首先引用AVFoundation.framework

.h文件

    AVAudioPlayer *player;

    //用到了拖控件(進度條)
    IBOutlet UIProgressView *_progressView;


.m文件

//此方法連接到一個已經拖在視圖上的button控件的觸發事件上

-(IBAction)play:(id)sender{

  //找到要播放的音頻
    NSString *_path=[[NSBundle mainBundle]pathForResource:@"張瑋-high歌 中國好聲音"ofType:@"mp3"];
    //文件的URL(如果是文件的URL,使用fileURLWithPath
    NSURL *_url=[NSURL fileURLWithPath:_path];
    NSError *error;
    player=[[AVAudioPlayer alloc]initWithContentsOfURL:_url
                                                            error:&error];
    if (error) {
        NSLog(@"error:%@",[error description]);
        return;
    }

//準備播放
    [player prepareToPlay];

//播放
    [player play];
    _progressView.progress=0.0f;

//用到了時間觸發器,刷新進度條
    [NSTimer scheduledTimerWithTimeInterval:0.5
                                     target:self
                                   selector:@selector(refreshUR:)
                                   userInfo:nil
                                    repeats:YES];
    
}

//刷新事件

-(void)refreshUR:(NSTimer *)aTimer{
    float p=player.currentTime/player.duration;//當前時間、總時間
    _progressView.progress=p;
}

//一下三個方法都是連接到已經佈置好的BUTTON觸發事件上的

//重新播放

-(IBAction)rePlay:(id)sender{
    player.currentTime=0.0f;
    [player play];

}

//暫停

-(IBAction)pause:(id)sender{
    [player pause];
}
//停止
-(IBAction)stop:(id)sender{
    if (player.isPlaying) {
        [player stop];
        player.currentTime=0.0f;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章