如何从开始播放AVAudioplayer?

时间:2015-03-25 10:20:08

标签: ios objective-c cocoa-touch avaudioplayer

我是Created AVAudio Player,它播放完美,点击播放按钮歌曲正在播放并显示暂停按钮,点击暂停按钮歌曲暂停并显示播放按钮,但点击播放按钮正在播放从开始.i想要播放简历歌曲。如何控制这个问题。这是我的代码,请检查一次。

-(void)playAudio
{
   // [progreetimer invalidate];
   // if([audioPlayer isPlaying]==YES)`enter code here`
    if(self.isPlaying)
    {
        [self.play setBackgroundImage:[UIImage imageNamed:@"audioplayer_play.png"]
        forState:UIControlStateNormal];
         NSLog(@"Pausing Music");
        if (self.progreetimer) {
            [self.progreetimer invalidate];
            progreetimer =nil;
        }
        [audioPlayer pause];
        self.isPlaying = NO;
    }

    else {

        // Init audio with playback capability
    [self.play setBackgroundImage:[UIImage imageNamed:@"audioplayer_pause.png"] forState:UIControlStateNormal];

   // NSString *urlstr = @"http://jesusredeems.in/media/Media Advt/mp3_player/Songs/viduthalaiyin geethangal_vol1/93.Ellame Koodum.mp3";

    NSString *urlstr =@"http://www.abstractpath.com/files/audiosamples/sample.mp3";
    urlstr = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlstr];
    NSData *data = [NSData dataWithContentsOfURL:url];
    audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
    audioPlayer.volume = 1.9f;
  //  [audioPlayer prepareToPlay];
    SongProgressBar.maximumValue = [audioPlayer duration];
    SongProgressBar.value = 0.0;
        NSLog(@"Playing music");

    //start a timer to update the time label display
    self.progreetimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
    selector:@selector(updateTime:) userInfo:nil repeats:YES];

    self.progreetimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
    selector:@selector(updateSlider) userInfo:nil repeats:YES];
    [progreetimer fire];
    audioPlayer.delegate=self;
    [audioPlayer play];
        self.isPlaying = YES;

    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];


    self.SongProgressBar.minimumValue = 30;

    self.SongProgressBar.maximumValue = 30;

    [self.SongProgressBar setThumbImage:[UIImage imageNamed:@"thumbslider.png"]

                        forState:UIControlStateNormal];

   // [self.SongProgressBar setThumbImage:[UIImage imageNamed:@"slider_icon.png"]

                      //  forState:UIControlStateHighlighted];

    [self.SongProgressBar setMinimumTrackImage:[UIImage imageNamed:@"slider_max.png"]

                               forState:UIControlStateNormal];

    [self.SongProgressBar setMaximumTrackImage:[UIImage imageNamed:@"slider_icon.png"]

                               forState:UIControlStateNormal];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [audioPlayer pause]; // Or pause
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [audioPlayer play];
}



- (IBAction)songprogressbar:(id)sender {
    // Fast skip the music when user scroll the UISlider
    [audioPlayer stop];
    [audioPlayer setCurrentTime:SongProgressBar.value];
    [audioPlayer prepareToPlay];
    [audioPlayer play];
}

- (IBAction)backword:(id)sender {
    if ([self.audioPlayer isPlaying]) {
        NSTimeInterval desiredTime = audioPlayer.currentTime -15.0f;
        if (desiredTime < 0) {
            audioPlayer.currentTime =0.0f;
        } else {
            audioPlayer.currentTime = desiredTime;
        }
    }
}

- (IBAction)play:(id)sender {

    [self playAudio];
}
- (void)updateSlider {
    // Update the slider about the music time
    SongProgressBar.value = audioPlayer.currentTime;
}

- (void)setCurrentAudioTime:(float)value {
    [self.audioPlayer setCurrentTime:value];
}
 //Stops the timer when the music is finished
- (void)audioPlayerDidFinishPlaying : (AVAudioPlayer *)player successfully : (BOOL)flag {
    // Music completed
    if (flag) {
        [progreetimer invalidate];

         NSLog(@"Finished playing the song");
    }
}

- (IBAction)forword:(id)sender {

    if ([audioPlayer isPlaying]) {
        NSTimeInterval desiredTime = audioPlayer.currentTime +15.0f;
        if (desiredTime < audioPlayer.duration) {
            audioPlayer.currentTime = desiredTime;
        }
    }
}

- (IBAction)volume:(id)sender {
     audioPlayer.volume=volume.value;
}

-(NSString*)timeFormat:(float)value{

    float minutes = floor(lroundf(value)/60);
    float seconds = lroundf((value) - (minutes * 60));

    int roundedSeconds = lroundf(seconds);
    int roundedMinutes = lroundf(minutes);

    NSString *time = [[NSString alloc]
                      initWithFormat:@"%d:%02d",
                      roundedMinutes, roundedSeconds];
    return time;

}
- (void)updateTime:(NSTimer *)timer {

        self.starttimer.text = [NSString stringWithFormat:@"%@",
        [self timeFormat: ceilf(audioPlayer.currentTime)]];


        self.endtimer.text = [NSString stringWithFormat:@"-%@", [self timeFormat: (audioPlayer.duration - ceilf(audioPlayer.currentTime))]];
    }

2 个答案:

答案 0 :(得分:1)

你应该试试这个。见 else 方法的一部分

-(void)playAudio
{
    // [progreetimer invalidate];
   // if([audioPlayer isPlaying]==YES)`enter code here`
    if(self.isPlaying)
    {
        //Code to pause audioPlayer
        [audioPlayer pause];
        self.isPlaying = NO;
    }

    else 
    {
            if(audioPlayer.url != nil && audioPlayer.duration != 0)
            {
                [audioPlayer play];
            }
            else
            {
                //Code to add new audioPlayer
            }
    }
}

答案 1 :(得分:-2)

使用以下代码

AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
[player prepareToPlay];
player.currentTime = 0;
[player play];
相关问题