2015-03-31 3 views
0

Я делаю приложение для будильника для iPhone и хочу непрерывно контура аудио до тех пор, пока кнопка не будет нажата снова. На данный момент все, что он делает, это воспроизведение звука один раз при нажатии. Вот код:Looping .wav file

-(IBAction)PlayAudioButton:(id)sender { 

AudioServicesPlaySystemSound(PlaySoundID); 

} 

- (void)viewDidLoad { 

NSURL *SoundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"wav"]]; 

AudioServicesCreateSystemSoundID((__bridge CFURLRef)SoundURL, &PlaySoundID); 

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

Любые предложения?

+2

Использовать AVAud ioPlayer. Вот для чего это! – matt

ответ

1

Используйте AVAudioPlayer, чтобы воспроизвести звук. Вы должны добавить AVFoundation.framework в свой проект, чтобы это сработало. Начните с объявления объекта AVAudioPlayer. Он должен быть объявлен как свойство с атрибутом strong, например.

@property (strong, nonatomic) AVAudioPlayer *audioPlayer; 

или как переменную экземпляра с атрибутом __strong

@interface Class : SuperClass //or @implementation Class 
{ 
    AVAudioPlayer __strong *audioPlayer; 
} 

Затем, чтобы загрузить и воспроизвести файл,

- (void)viewDidLoad 
{ 
    NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"wav"]; 
    NSURL *audioFileURL = [NSURL fileURLWithString:audioFilePath]; 
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:nil]; 
    audioPlayer.numberOfLoops = -1; //plays indefinitely 
    [audioPlayer prepareToPlay]; 
} 


- (IBAction)PlayAudioButton:(id)sender 
{ 
    if ([audioPlayer isPlaying]) 
     [audioPlayer pause]; //or "[audioPlayer stop];", depending on what you want 
    else 
     [audioPlayer play]; 
} 

и, если вы хотите, чтобы остановить воспроизведение звука, звонок

[audioPlayer stop];