简体   繁体   English

Objective-C / iPhone中的音频循环

[英]Audio looping in Objective-C/iPhone

So, I'm finishing up an iPhone App. 因此,我正在完成一个iPhone App。

I have the following code in place to play the file: 我具有以下代码来播放文件:

while(![player isPlaying]) {
  totalSoundDuration = soundDuration + 0.5; //Gives a half second break between sounds
  sleep(totalSoundDuration); //Don't play next sound until the previous sound has finished
  [player play]; //Play sound
  NSLog(@" \n Sound Finished Playing \n"); //Output to console
}

For some reason, the sound plays once then the code loops and it outputs the following: 由于某种原因,声音播放一次,然后代码循环,并输出以下内容:

Sound Finished Playing
Sound Finished Playing
Sound Finished Playing
etc...

This just repeats forever, I don't suppose any of you lovely people can fathom what could be the boggle? 这只是永远的重复,我不认为你们中任何一个可爱的人都能理解可能是什么?

Cheers! 干杯!

I am not exactly sure what's wrong with your code, it could be that [player play] is an asyncronous call, but you loop forever without letting the player to actually start playing or realizing that it is actually playing. 我不确定您的代码有什么问题,可能是[player play]是一个异步调用,但是您永远循环播放,而没有让Player真正开始玩或意识到它实际上在玩。 I don't recommend using sleep in any iPhone applications, because the whole model is based on asynchronous events. 我不建议在任何iPhone应用程序中使用sleep,因为整个模型基于异步事件。

I did not test this code or even compile it, but I hope you get the idea from it. 我没有测试甚至没有编译过此代码,但我希望您能从中得到启发。

- (void) startPlayingAgain:(NSTimer *)timer
{
    AVAudioPlayer *player = timer.userInfo;

    [player play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player 
                       successfully:(BOOL)flag
{
  NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
                            target:self
                            selector:@selector(startPlayingAgain:)
                            userInfo:player
                            repeats:NO];
}

- (void)startPlaying:(NSString *)url
{
    AVAudioPlayer *player = [[AVAudioPlayer alloc] 
                                initWithContentsOfURL:url error:NULL];

    player.delegate = self;

    [player play];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM