问题
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.
回答1:
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?
回答2:
For a short delay, where you can tell the AVAudioPlayer to start playing now but with a delay, you don't use NSDate (the value returned from a UIDatePicker) to do this. That's not how an AVAudioPlayer thinks about time. It thinks in terms of device time.
So, you need to work out how long from the current device time the playing should start. That way, you can call the audio player's playAtTime:
with that value. There's an example in the documentation:
https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerClassReference/#//apple_ref/occ/instm/AVAudioPlayer/playAtTime:
For a long delay, where you need to start playing, say, tomorrow at 10 AM, you need to create a UINotification that will fire at that time. This can include a sound; if that isn't good enough, you'll have to hope that either your app is running (so that you can receive the notification) or that the user taps the notification when it appears (so that you can hear about that) - otherwise, as Duncan says, you can't do it.
来源:https://stackoverflow.com/questions/32685977/how-to-get-audio-to-play-at-time-from-nsdatepicker