Воспроизведение музыки в фоновом режиме с помощью AVAudioplayer
Я хочу играть музыку, даже если приложение идет в фоновом режиме. Я проверил все ссылки на stackoverflow, но ни один из них не работал. Пожалуйста, помогите сделать это сегодня.
Я использовал следующий код: -
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Day At The Beach" ofType: @"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
NSError *error;
playerTemp = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
playerTemp.numberOfLoops = 0;
AudioSessionSetActive(true);
[playerTemp play];
Ответы
Ответ 1
Я решил этот вопрос, обратившись к IOS Application Background tasks
и внесите некоторые изменения в файл .plist
нашего приложения.
Обновление
напишите этот код в представлении вашего контроллера, загрузите метод, подобный этому
- (void)viewDidLoad
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"in-the-storm" ofType:@"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer play];
[super viewDidLoad];
}
Ответ 2
Я просто хотел добавить примечание к ответу Мехула. Эта строка:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
на самом деле очень важно. Я использовал другие уроки, чтобы запустить мой AVAudioPlayer. Все отлично работало, за исключением того, что мой звук не начинался, если приложение было в фоновом режиме. Чтобы уточнить, мой звук был в порядке, если он уже играл, когда приложение зашло в фоновом режиме... но оно не запустится, если приложение уже было в фоновом режиме.
Добавление вышеприведенной строки кода привело к тому, что мой звук начнется, даже если приложение было в фоновом режиме.
Ответ 3
Вам нужно установить "audio" как один из ваших UIBackgroundModes в Info.plist. У Apple есть документация по проблеме.
Ответ 4
Вы можете использовать MPMoviePlayerController даже для воспроизведения соло-аудио-фильмов. Если вам это нравится, прочитайте эту подробную техническую информацию Apple Library Q & A:
Библиотека разработчиков iOS Технический Q & A QA1668
Ответ 5
Также важно, если вы используете MPMusicPlayerController
:
Вы должны использовать:
[MPMusicPlayerController iPodMusicPlayer]
И не
[MPMusicPlayerController applicationMusicPlayer]
Также, если вы не хотите, чтобы ваше приложение было stop music
, которое воспроизводилось при запуске приложения, смотрите здесь:
AVAudioPlayer отключает iPod - как обойти?
Ответ 6
Запишите эту строку в plist для запуска фона...
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
Введите этот код, где вы хотите использовать
AVAudioPlayer* audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.urlForConevW error:&error];
audioPlayer.delegate = self;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
audioPlayer.numberOfLoops = 1;
[audioPlayer play];
Ответ 7
Step1
Внесите следующие изменения в info.plist
-
Приложение не работает в фоновом режиме: NO
-
Необходимые фоновые режимы
item0 :App plays audio or streams audio/video using AirPlay
Шаг 2
Не забудьте добавить следующие вещи в файл MainViewController.h
Шаг 3
Добавьте следующий код внутри действия воспроизведения вашего класса MainViewController
.
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d-%d",C_CID, C_SID] ofType:@"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
H_audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
H_audio_player.delegate = self;
H_audio_player.numberOfLoops = -1;
Ответ 8
Если даже после установки звука в качестве одного из ваших UIBackgroundModes
в plist звук останавливается при переходе на задний план, попробуйте setting
ваш application audio session
на media playback
.
Вот ссылка:
https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Introduction/Introduction.html
Вот о чем будет выглядеть код:
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
NSError*setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
Ответ 9
Я использую приведенный ниже код. Он работает для меня и вызывается нажатием кнопки метода экземпляра аудиоплеера.
NSError *error; NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"]];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
[[AVAudioSession sharedInstance] setActive:YES error: &error];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self.player prepareToPlay];
Ответ 10
Из всех ответов отсутствует этот код для управления проигрывателем, когда пользователь пробуждает устройство:
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch (event.subtype) {
case UIEventSubtypeRemoteControlPlay:
[_audioPlayer play];
break;
case UIEventSubtypeRemoteControlPause:
[_audioPlayer pause];
break;
default:
break;
}
}
И у вас есть все эти опции:
UIEventSubtypeRemoteControlPlay = 100,
UIEventSubtypeRemoteControlPause = 101,
UIEventSubtypeRemoteControlStop = 102,
UIEventSubtypeRemoteControlTogglePlayPause = 103,
UIEventSubtypeRemoteControlNextTrack = 104,
UIEventSubtypeRemoteControlPreviousTrack = 105,
UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
UIEventSubtypeRemoteControlEndSeekingBackward = 107,
UIEventSubtypeRemoteControlBeginSeekingForward = 108,
UIEventSubtypeRemoteControlEndSeekingForward = 109,
Ответ 11
Воспроизведение аудио в фоновом режиме
Шаг 1: просто добавьте в свой файл info.plistmake массив
![enter image description here]()
step2:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
__block UIBackgroundTaskIdentifier task = 0;
task=[application beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Expiration handler called %f",[application backgroundTimeRemaining]);
[application endBackgroundTask:task];
task=UIBackgroundTaskInvalid;
}];
}
step3:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"iNamokar" ofType:@"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[player prepareToPlay];
[self.player play];
Ответ 12
Из примера кода Apple: Audio Mixer (MixerHost)
// If using a nonmixable audio session category, as this app does, you must activate reception of
// remote-control events to allow reactivation of the audio session when running in the background.
// Also, to receive remote-control events, the app must be eligible to become the first responder.
- (void) viewDidAppear: (BOOL) animated {
[super viewDidAppear: animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
Я думаю, что события дистанционного управления не нужны для следующего случая:
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers,
sizeof(value), &value);