iosavaudioplayernsdatepicker

How to get audio to play at time from NSDatePicker?


I'm making an app which requires a sound to play at a time in the future set by the user using NSDatePicker how would I do so?

I already have the AVAudioPlayer setup, I just need the help with the playing itself. And please write how to do so that answers the entire question instead of leading me elsewhere.

The aim is to get an alarm that can be set by the user at a specific time using NSDatePicker and using a sound I have made and added to the project. And then for the user to have to turn the alarm off itself not an automatic turn off. So I was going to use AVAudioPlayer and an off button to do so but I couldn't get past the timing.


Solution

  • Short answer: You can't do that.

    An iPhone is only unlocked part of the time, and your app is only running part of the time.

    If you are talking about making a sound play a few minutes in the future, while the phone is awake, and the app is still in the foreground, that you could do.

    You'd just need to take the NSDate from the date picker, use the NSDate method timeIntervalSinceNow to figure out how many seconds in the future that date is, and then start an NSTimer who's selector plays your sound.

    If your app might be suspended, or the phone might be locked, you'll need to use a local notification (UILocalNotification). The notification just displays a message to the user (possibly playing a sound that is shipped with your app.) I guess if the sound you want to play is included with the app then you could set up your local notification to play it.

    Can you tell us more about what you want to do?

    Do you want this to work at any arbitrary date and time in the future? Do you need to play a sound that is built into your app?