Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform operations when playing sound in iPhone?

I play a MP3 in my iPhone app using AVAudioPlayer; i need to perform some operations at certain times (say 30th seconds, 1 minute); is there a way to invoke callback functions based on mp3 playing time?

like image 728
Cris Avatar asked May 11 '12 20:05

Cris


People also ask

How do I fix the sound on my iPhone?

Go to Settings > Sounds (or Settings > Sounds & Haptics), and drag the Ringer and Alerts slider back and forth a few times. If you don't hear any sound, or if your speaker button on the Ringer and Alerts slider is dimmed, your speaker might need service.

How do I change the speaker settings on my iPhone?

Go to Settings > Accessibility > Audio/Visual > Headphone Accommodations. Tap Custom Audio Setup. Follow the instructions on your screen. When finished, tap Use Custom Settings to apply the custom settings suggested based on your choices.


2 Answers

I believe the best solution is to start an NSTimer as you start the AVAudioPlayer playing. You could set the timer to fire every half second or so. Then each time your timer fires, look at the currentTime property on your audio player.

In order to do something at certain intervals, I'd suggest you kept an instance variable for the playback time from last time your timer callback was called. Then if you had passed the critical point between last callback and this, do your action.

So, in pseudocode, the timer callback:

  1. Get the currentTime of your AVAudioPlayer
  2. Check to see if currentTime is greater than criticalPoint
  3. If yes, check to see if lastCurrentTime is less than criticalPoint
  4. If yes to that too, do your action.
  5. Set lastCurrentTime to currentTime
like image 54
Amy Worrall Avatar answered Oct 20 '22 00:10

Amy Worrall


If you're able to use AVPlayer instead of AVAudioPlayer, you can set boundary or periodic time observers:

// File URL or URL of a media library item
AVPlayer *player = [[AVPlayer alloc] initWithURL:url];        

CMTime time = CMTimeMakeWithSeconds(30.0, 600);
NSArray *times = [NSArray arrayWithObject:[NSValue valueWithCMTime:time]];

id playerObserver = [player addBoundaryTimeObserverForTimes:times queue:NULL usingBlock:^{
    NSLog(@"Playback time is 30 seconds");            
}];

[player play];

// remove the observer when you're done with the player:
[player removeTimeObserver:playerObserver];

AVPlayer documentation: http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVPlayer_Class/Reference/Reference.html

like image 28
mrwalker Avatar answered Oct 19 '22 23:10

mrwalker