首页 文章

iOS通过AVPlayer将音频播放添加到OS默认播放器?

提问于
浏览
4

因此我们的想法是 - 当我们在iPhone中的音乐应用程序中播放音频并按下主页按钮然后从屏幕底部滑动时,我们可以看到在默认操作系统播放器中播放的音频具有播放/暂停控制和音频继续播放 .

现在我需要做什么,我在我的应用程序中使用 AVAudioPlayer 播放音频,如果用户按下主页按钮,音频需要继续播放,如同音乐应用程序一样 . 但我不知道如何在OS默认播放器中添加音频?任何帮助或建议将受到高度赞赏 .

Edit: 我需要使用流媒体播放音频,所以我想我需要使用 AVPlayer 而不是 AVAudioPlayer

2 回答

  • 3

    您可以将此作为后台音频任务执行此操作,以便即使在用户按下主页按钮并且您的应用程序进入后台后,音频仍会继续播放 . 首先,您创建一个AVAudioSession . 然后在viewDidLoad方法中设置一个AVPlayerObjects数组和一个AVQueuePlayer . Ray Wenderlich有一个很棒的教程,详细讨论了所有这些http://www.raywenderlich.com/29948/backgrounding-for-ios . 您可以设置一个回调方法(观察者方法),以便在应用程序流入时发送其他音频数据 - (void)observeValueForKeyPath .

    以下是代码的外观(来自Ray Wenderlich的教程):

    在viewDidLoad中:

    // Set AVAudioSession
    NSError *sessionError = nil;
    [[AVAudioSession sharedInstance] setDelegate:self];
    [[AVAudioSession sharedInstance]     setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    // Change the default output audio route
    UInt32 doChangeDefaultRoute = 1;
    AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
      sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
    
    NSArray *queue = @[
    [AVPlayerItem playerItemWithURL:[[NSBundle mainBundle]  URLForResource:@"IronBacon" withExtension:@"mp3"]],
    [AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"FeelinGood" withExtension:@"mp3"]],
    [AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"WhatYouWant" withExtension:@"mp3"]]];
    
    self.player = [[AVQueuePlayer alloc] initWithItems:queue];
    self.player.actionAtItemEnd = AVPlayerActionAtItemEndAdvance;
    
    [self.player addObserver:self
                  forKeyPath:@"currentItem"
                     options:NSKeyValueObservingOptionNew
                     context:nil];
    

    在回调方法中:

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if ([keyPath isEqualToString:@"currentItem"])
        {
            AVPlayerItem *item = ((AVPlayer *)object).currentItem;
            self.lblMusicName.text = ((AVURLAsset*)item.asset).URL.pathComponents.lastObject;
            NSLog(@"New music name: %@", self.lblMusicName.text);
        }
    }
    

    不要忘记在实现文件的视图控制器的私有API中添加成员变量:

    @interface TBFirstViewController ()
    
    @property (nonatomic, strong) AVQueuePlayer *player;
    @property (nonatomic, strong) id timeObserver; 
    @end
    
  • 1

    您可以使用MPMovieplayerController,因为您很可能正在使用M3U8播放列表 .

    这是文档http://developer.apple.com/library/ios/documentation/MediaPlayer/Reference/mpmovieplayercontroller_class/index.html

    但它基本上是这样的:

    初始化MPMoviePlayerController,分配文件类型(流),放置源URL,并将其显示在视图堆栈中 .

    对于背景音频,你必须像在这个答案中使用AudioSession iOS MPMoviePlayerController playing audio in background

相关问题