如何从开始播放音频播放器?

Posted

技术标签:

【中文标题】如何从开始播放音频播放器?【英文标题】:How to Play AVAudio player from Starting? 【发布时间】:2015-03-25 10:20:07 【问题描述】:

我是创建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))]];
    

【问题讨论】:

当您的AVAudioPlayer 实例被暂停并且playAudio 被调用时,您将创建一个AVAudioPlayer 的新实例,丢弃前一个暂停的实例。您应该检测AVAudioPlayer 的播放状态,并在暂停时重新开始播放。 如何改变那个? 【参考方案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
            
    

【讨论】:

它不起作用兄弟。 if 语句不调用。你能改一下代码吗? 您是否将audioPlayer定义为全局常量?如果不是将其定义为全局!因为这段代码对我有用【参考方案2】:

使用以下代码

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

【讨论】:

问题不是关于如何创建AVAudioPlayer 并播放音乐,而是关于暂停它稍后继续播放。 需要将玩家当前时间归零

以上是关于如何从开始播放音频播放器?的主要内容,如果未能解决你的问题,请参考以下文章

当另一个应用开始播放音频时,如何自动暂停我的应用中的音频播放器?

如何从实时流中播放音频

如何在 iOS 中从开始时间到结束时间修剪或播放音频?

在 vue 中构建音频播放器;如何在更改绑定后开始播放音频:src?

如何在 iOS 中使用原始数据播放音频?

定位速度降低时播放音频播放器