私はAppStoreでほぼ同じアプリをリリースしました。 [MPMusicPlayerController applicationMusicPlayer]を使用して曲を再生します。
はい、MPMusicPlayerControllerPlaybackStateDidChangeNotificationはバックグラウンドアプリにはなりませんでした。 それで、NSTimerを使って曲がいつ終了するかを判断しました。 NSTimerを1秒に設定しています。私はNSTimerを曲の演奏時間に設定しました。すなわち、曲が3分15秒の時間を有するとき、NSTimerを3分15秒に設定する。
ユーザーが音楽を一時停止すると、NSTimerが一時停止します。 そして、ユーザーが音楽を再開すると、NSTimerを曲の残りの時間に設定します。
非常にうまく動作します。 これがあなたを助けてくれることを願っています。 申し訳ありませんが私のcheepの英語です。
手順が必要な場合があります。
- 機能設定でオーディオ背景モードを設定します。 (完了しました)
- App DelegateでbeginBackgroundTaskWithExpirationHandlerを使用します。非繰り返しモードで
- (void)applicationWillResignActive:(UIApplication *)application
{
_bgid = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void)
{
[[UIApplication sharedApplication] endBackgroundTask:_bgid];
_bgid = UIBackgroundTaskInvalid;
}];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
if (_bgid != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:_bgid];
}
}
3.Use NSTimer。今後の参考のために
#import "NMCountdownTimer.h"
@interface NMCountdownTimer()
{
@private
NSTimer *_timer;
NSTimeInterval _rest;
NMMethodCompletion _completion;
}
@end
@implementation NMCountdownTimer
- (void)start:(NSTimeInterval)secs completion:(NMMethodCompletion _Nullable)completion
{
_completion = completion;
if (secs > 0.0f)
{
NSLog(@"[ ] start (secs:%f)", secs);
_timer = [NSTimer scheduledTimerWithTimeInterval:secs target:self selector:@selector(fired) userInfo:nil repeats:FALSE];
_rest = 0.0f;
}
}
- (void)pause
{
if (_timer && (_rest == 0.0f))
{
_rest = [[_timer fireDate] timeIntervalSinceReferenceDate] - [[NSDate date] timeIntervalSinceReferenceDate];
NSLog(@"[ ] pause (rest:%f)", _rest);
[_timer invalidate];
_timer = nil;
}
}
- (void)resume
{
if ((! _timer) && (_rest > 0.0f))
{
NSLog(@"[ ] resume (rest:%f)", _rest);
_timer = [NSTimer scheduledTimerWithTimeInterval:_rest target:self selector:@selector(fired) userInfo:nil repeats:FALSE];
_rest = 0.0f;
}
}
- (void)kill
{
[_timer invalidate];
_timer = nil;
_rest = 0.0f;
_completion = nil;
NSLog(@"[ ] kill");
}
- (void)fired
{
[_timer invalidate];
_timer = nil;
_rest = 0.0f;
if (_completion)
{
_completion (nil);
}
NSLog(@"[ ] fired");
}
- (void)dealloc
{
#if (Namera_SHOW_DEALLOC && FALSE)
NSLog(@"[DEA] %@ NMCountdownTimer", self);
#endif
_timer = nil;
_completion = nil;
}
@end
somewhere in your code like this;
NSTimeInterval playback_duration = [[song valueForProperty: MPMediaItemPropertyPlaybackDuration] doubleValue];
....
MPMediaItemCollection *collection = [MPMediaItemCollection collectionWithItems:[NSArray arrayWithObject:song]];
[_musicCtr setQueueWithItemCollection:collection];
[_musicCtr play];
[_countdown_timer start:playback_duration completion:^(id _Nullable object)
{
[weakSelf execute_next_song];
}];
繰り返しモードのNSTimerはバックグラウンドでうまく動作しないと思います。私は非繰り返しモードで使用しました。 –
全く同じことを試しましたが、3分後にNSTimerが起動しなくなりました。だから私の本当の疑問は、どうすれば3分以上かかるのだろうか?オーディオ背景モードが設定されています。 –