如果用户单击播放按钮,如何在AVAudioPlayer中显示加载指示器

时间:2014-04-10 05:32:11

标签: ios iphone objective-c avaudioplayer

我在iOS的AVAudioplayer工作。如果用户点击播放按钮,我正在显示加载时间的活动指示器。我的问题是,当我点击播放按钮时,不会显示加载时间活动指示器。

-(void)loadData

{

url=[NSURL URLWithString:@"http://www.urls.com"];

NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];

[[NSURLConnection alloc]initWithRequest:request delegate:self];

[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;

[self.view addSubview:loadingView];

[activityView startAnimating];

loadingConnection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];

}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

responseData=[[NSMutableData alloc]init];

[responseData setLength:0];

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

if(connection==loadingConnection)

{

[responseData appendData:data];

}

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;

[activityView stopAnimating];

[loadingView removeFromSuperview];

if(connection==loadingConnection)

{

NSError *jsonError = nil;

id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&jsonError];

if ([jsonObject isKindOfClass:[NSArray class]])

{

//NSArray *jsonArray = (NSArray *)jsonObject;

}

else if ([jsonObject isKindOfClass:[NSDictionary class]])

{

NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;

NSArray *array=[[NSArray alloc]init];

array=[jsonDictionary objectForKey:@"audio-urls"];

dataDictionary=[array objectAtIndex:0];

NSLog(@"%@",dataDictionary);

}

[urlsArray addObject:[dataDictionary objectForKey:@“Audio1”]];

[urlsArray addObject:[dataDictionary objectForKey:@“Audio2”]];

[urlsArray addObject:[dataDictionary objectForKey:@“Audio3”]];

[urlsArray addObject:[dataDictionary objectForKey:@“Audio4”]];

[urlsArray addObject:[dataDictionary objectForKey:@“Audio5”]];

[urlsArray addObject:[dataDictionary objectForKey:@“Audio6”]];

NSLog(@"%@",urlsArray);

}

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"Please ensure you have internet connection" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alert show];

[activityView stopAnimating];

[loadingView removeFromSuperview];

}

- (void)viewDidLoad

{

playing=NO;

[self loadData];

//  [self temp];

[self performSelector:@selector(loadData) withObject:nil afterDelay:3.0f];

urlsArray=[[NSMutableArray alloc]init];

[super viewDidLoad];

}    

-(void)temp

{

// loading View

loadingView=[[UILabel alloc]initWithFrame:CGRectMake(135, 200, 40, 40)];

loadingView.backgroundColor=[UIColor clearColor];

loadingView.clipsToBounds=YES;

loadingView.layer.cornerRadius=10.0;

activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];

activityView.frame = CGRectMake(10, 11, activityView.bounds.size.width, activityView.bounds.size.height);

[loadingView addSubview:activityView];

}


-(void)playOrPauseButtonPressed:(id)sender

{

if(playing==NO)

{

[self temp];

// [self.view addSubview:loadingView];

//   [loadingView addSubview:activityView];

// [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;

[playButton setBackgroundImage:[UIImage imageNamed:@"Pause.png"] forState:UIControlStateNormal];

// Here Pause.png is a image showing Pause Button.

NSError *err=nil;

AVAudioSession *audioSession=[AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

NSLog(@"%@ %d",urlsArray,selectedIndex);

NSString *sourcePath=[urlsArray objectAtIndex:selectedIndex];

NSData *objectData=[NSData dataWithContentsOfURL:[NSURL URLWithString:sourcePath]];

NSLog(@"%@",objectData);

audioPlayer = [[AVAudioPlayer alloc] initWithData:objectData error:&err];

if(err)

{

NSLog(@"Error %ld,%@",(long)err.code,err.localizedDescription);

}

NSTimeInterval bufferDuration=0.005;

[audioSession setPreferredIOBufferDuration:bufferDuration error:&err];

if(err)

{

NSLog(@"Error %ld, %@", (long)err.code, err.localizedDescription);

}

double sampleRate = 44100.0;

[audioSession setPreferredSampleRate:sampleRate error:&err];

if(err)

{

NSLog(@"Error %ld, %@",(long)err.code,err.localizedDescription);

}

[audioSession setActive:YES error:&err];

if(err)

{

NSLog(@"Error %ld,%@", (long)err.code, err.localizedDescription);

}

sampRate=audioSession.sampleRate;

bufferDuration=audioSession.IOBufferDuration;

NSLog(@"SampeRate:%0.0fHZI/OBufferDuration:%f",sampleRate,bufferDuration);

audioPlayer.numberOfLoops = 0;

[audioPlayer prepareToPlay];

[audioPlayer play];

audioPlayer.delegate=self;

if(!audioPlayer.playing)

{

[audioPlayer play];

}

playing=YES;

}

else if (playing==YES)

{

[playButton setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];

[audioPlayer pause];

playing=NO;

timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateViewForPlayerState) userInfo:nil repeats:YES];

}

if (self.audioPlayer)

{

[self updateViewForPlayerInfo];

[self updateViewForPlayerState];

[self.audioPlayer setDelegate:self];

}

}

2 个答案:

答案 0 :(得分:0)

无需NSURLConnection委托方法 在AVAudioPlayer中直接传递URL

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [spinner setCenter:CGPointMake(230, 330)]; // I do this because I'm in landscape mode
    [yourview addSubview:spinner];
    [spinner setColor:[UIColor whiteColor]];
 [spinner startAnimating];

  [self performSelector:@selector(download) withObject:nil afterDelay:0.50f];



    -(void)download
    {    


    NSData *audioData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.dailywav.com/0813/bicycles.wav"]];
    NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/bicycles.wav", docDirPath ];
    [audioData writeToFile:filePath atomically:YES];

    NSError *error;
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
    if (player == nil) {
        NSLog(@"AudioPlayer did not load properly: %@", [error description]);
    } else {
  [spinner stopAnimating
     ];
        [player play];
    }
    }

答案 1 :(得分:0)

//创建并添加活动指标以进行查看

UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; 
activityIndicator.alpha = 1.0; 
activityIndicator.center = CGPointMake(160, 360); 
activityIndicator.hidesWhenStopped = NO; 
[self.view addSubview:activityIndicator]; 
[activityIndicator startAnimating];`

度过美好的一天!