开发者

Can you see anything wrong in this code?

开发者 https://www.devze.com 2022-12-19 07:21 出处:网络
NSString *path = [[NSBundle mainBundle] pathForResource:[arraySub objectAtIndex:indexPathHere.row] ofType:@\"mp3\"];
NSString *path = [[NSBundle mainBundle] pathForResource:[arraySub objectAtIndex:indexPathHere.row] ofType:@"mp3"];
NSURL *file = [[NSURL alloc] init开发者_运维问答FileURLWithPath:path];
AVAudioPlayer *myPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
self.player = myPlayer;
[player prepareToPlay];
[player setDelegate:self];
[self.player play];

NSTimeInterval lenghtMusic = player.duration;

if (player.currentTime == lenghtMusic) {
 NSLog(@"It worked");
 [tableThing deselectRowAtIndexPath:indexPathHere animated:YES];
 [myPlayer autorelease];
 [file autorelease];
}

Can you see anything wrong?

Apparently, the "if"-statement never gets called...


If I read your code correctly you are trying to find out when the player has finished playing and then you want to deselect the current rode and release the player. Your problem is that you start the player and then immediately checks where it is currently playing. Unless you have an almost 0 length file the currentTime and length will NEVER be equal.

If that is what you are trying to do you should use the AVAudioPlayerDelegate Protocol and especially the:

– audioPlayerDidFinishPlaying:successfully:

method that is called when the player is finished.

So you need to change your class that controls the player by editing the .h file to use the AVAudioPlayerDelegate Protocol. Obviously keep extending whatever you were before.

@interface YourClass <AVAudioPlayerDelegate>

@end

In your .m file: Then when you have created and assigned your player instance:

[player setDelegate:self];

In the .m file also add the method

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    // Your success code goes here
}


You are comparing double's with ==, which is almost always false due to round-off errors.

Compare with a range e.g.

if (fabs(player.currentTime - lenghtMusic) < 0.0001) {
  ...
}


I'm a noob iPhone dev, but are you sure that player.currentTime is a NSTimeInterval? That looks like the most obvious candidate.

Also, I'd log out what your player.currentTime is and what lenghtMusic is before your if and that'll probably let you know what's going on.

0

精彩评论

暂无评论...
验证码 换一张
取 消