2014-11-06 3 views
1

Я пытаюсь создать приложение, которое будет воспроизводить некоторые аудиофайлы. Я надеялся передать аудио с веб-сервера, но до сих пор я помещаю mp3 прямо в проект, так как не знаю, как установить ссылку на http urls.AVAudioPlayer не возобновляется при нажатии кнопки остановки

Я создал кнопку остановки, и я понимаю, что если вы нажмете стоп, а затем снова запустите, файл mp3 должен возобновиться с того места, где он остановился. Это не для меня. Какие-нибудь подсказки относительно того, что я сделал неправильно, пожалуйста? Я также попытался использовать паузу, а также без изменений. Спасибо заранее. Код из моего файла .h приведен ниже.

Также, что мне нужно сделать, если я хочу иметь несколько аудиофайлов?

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 
AVAudioPlayer *player; 

- (void)viewDidLoad { 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 
} 

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

- (IBAction)play:(id)sender { 
NSURL *songURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"hustle"  ofType:@"mp3"]]; 
player = [[AVAudioPlayer alloc] initWithContentsOfURL:songURL error:nil]; 
player.volume = 0.5; 
[player play]; 

} 

- (IBAction)pause:(id)sender { 
[player stop]; 
} 

- (IBAction)volumeChanged:(id)sender { 
player.volume = volumeSlider.value; 

} 


@end 

Вот отредактированный .m файл с массивом:

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

AVAudioPlayer *player; 

- (void)viewDidLoad { 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 

//NSURL *songURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"hustle"  ofType:@"mp3"]]; 
//player = [[AVAudioPlayer alloc] initWithContentsOfURL:songURL error:nil]; 
//player.volume = 0.5; 

songsArray = [[NSMutableArray alloc] initWithObjects:@"hustle", @"hustle2", nil]; 
NSUInteger currentTrackNumber; 
currentTrackNumber=0; 

} 

- (IBAction)startPlaying 
{ 
if (player) { 
    [player stop]; 
    player = nil; 
} 
player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[[NSString alloc] initWithString:[songsArray objectAtIndex:currentTrackNumber]] ofType:@"mp3"]] error:NULL]; 
player.delegate = self; 
[player play]; 
} 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player1 successfully:(BOOL)flag 
{ 
if (flag) { 
    if (currentTrackNumber < [songsArray count] - 1) { 
     currentTrackNumber ++; 
     if (player) { 
      [player stop]; 
      player = nil; 
     } 
     player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:[[NSString alloc] initWithString:[songsArray objectAtIndex:currentTrackNumber]] ofType:@"mp3"]] error:NULL]; 
     player.delegate = self; 
     [player play]; 
    } 
} 
} 

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

- (IBAction)play:(id)sender { 

[player play]; 

} 

- (IBAction)pause:(id)sender { 
[player stop]; 
} 

- (IBAction)volumeChanged:(id)sender { 
player.volume = volumeSlider.value; 

} 

@end 
+2

вы должны сделать паузу вместо очистных, '[игрок пауза],', то вы должны играть снова, чтобы возобновить его. – zaheer

ответ

1
Write the code like this, when you click on the pause button the audio stopped then click on the play button the audio will resumed where the audio stopped.  



- (void)viewDidLoad { 
     [super viewDidLoad]; 
     // Do any additional setup after loading the view, typically from a nib. 

     NSURL *songURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"hustle"  ofType:@"mp3"]]; 
     player = [[AVAudioPlayer alloc] initWithContentsOfURL:songURL error:nil]; 
     player.volume = 0.5; 
    } 

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

    - (IBAction)play:(id)sender { 

     [player play]; 

    } 

    - (IBAction)pause:(id)sender { 
     [player stop]; 
    } 
+0

Спасибо Суреш - это исправило мою проблему! Есть ли какие-либо рекомендации, которые вы можете дать мне, если я хочу сыграть более 1 аудиофайла, пожалуйста? Я хотел бы добавить еще несколько аудиофайлов в мой проект. – user3934210

0

@ user3934210

Возьмите массив в файл .h и написать протокол делегата для игрока

"AVAudioPlayerDelegate>"

NSMutableArray *songsArray; 

в .m файлов

Add all the .mp3 songs to the array in viewDidLoad 

songsArray = [[NSMutableArray alloc]initWithObjects:@“A”,@“B”,@“C”,nil]; //replace your files 

then take one Integer value to find the current song 
    NSUInteger currentTrackNumber; 

and set the currentTrackNumber=0 in viewDidLoad, 

then copy the below code 

- (IBAction)startPlaying 
{ 
    if (player) { 
     [player stop]; 
     player = nil; 
    } 
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[[NSString alloc] initWithString:[songsArray objectAtIndex:currentTrackNumber]] ofType:@"mp3"]] error:NULL]; 
    player.delegate = self; 
    [player play]; 
} 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player1 successfully:(BOOL)flag 
{ 
    if (flag) { 
     if (currentTrackNumber < [songsArray count] - 1) { 
      currentTrackNumber ++; 
      if (player) { 
       [player stop]; 
       player = nil; 
      } 
      player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[[NSString alloc] initWithString:[songsArray objectAtIndex:currentTrackNumber]] ofType:@"mp3"]] error:NULL]; 
      player.delegate = self; 
      [player play]; 
     } 
    } 
} 
+0

Входит ли этот код в файл .h? Извините, вам трудно читать, поскольку вы добавили обычный текст в поле кода. Спасибо за помощь снова. – user3934210

+0

Проверьте приведенный выше код –

+0

Спасибо за разъяснение. – user3934210

Смежные вопросы