gpt4 book ai didi

iphone - 在 iPhone 上播放背景音频

转载 作者:行者123 更新时间:2023-12-03 19:32:53 24 4
gpt4 key购买 nike

如何在应用程序运行时播放背景音频?

谢谢。

最佳答案

好的。这是 iOS4 和 iOS5 上背景声音的解决方案(绝对适用于 iOS 5.0.1),我仅使用 AVPlayer 对其进行了测试。它可能也适用于 MPMusicPlayerController。

所需框架:

  • AVFoundation.framework
  • AudioToolbox.framework

在您的 Info.plist 中,对于 key UIBackgroundModes ,添加audio .

MyAppDelegate.h :

  • 引用<AVFoundation/AVFoundation.h> & <AudioToolbox/AudioToolbox.h>
  • 实现协议(protocol)AVAudioSessionDelegate :

    @interface MyAppDelegate : NSObject <UIApplicationDelegate, AVAudioSessionDelegate>
  • 定义一个方法 ensureAudio :

    // Ensures the audio routes are setup correctly
    - (BOOL) ensureAudio;

MyAppDelegate.m :

  • 实现ensureAudio方法:

    - (BOOL) ensureAudio
    {
    // Registers this class as the delegate of the audio session (to get background sound)
    [[AVAudioSession sharedInstance] setDelegate: self];

    // Set category
    NSError *categoryError = nil;
    if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&categoryError]) {
    NSLog(@"Audio session category could not be set");
    return NO;
    }

    // Activate session
    NSError *activationError = nil;
    if (![[AVAudioSession sharedInstance] setActive: YES error: &activationError]) {
    NSLog(@"Audio session could not be activated");
    return NO;
    }

    // Allow the audio to mix with other apps (necessary for background sound)
    UInt32 doChangeDefaultRoute = 1;
    AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);

    return YES;
    }
  • application:didFinishLaunchingWithOptions:方法,在分配 Root View Controller 之前,运行 [self ensureAudio] :

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    // Configure audio session
    [self ensureAudio];

    // Add the navigation controller's view to the window and display.
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];

    return YES;
    }
  • 实现AVAudioSessionDelegate像这样的方法:

    #pragma mark - AVAudioSessionDelegate

    - (void) beginInterruption
    {

    }

    - (void) endInterruption
    {
    // Sometimes the audio session will be reset/stopped by an interruption
    [self ensureAudio];
    }

    - (void) inputIsAvailableChanged:(BOOL)isInputAvailable
    {

    }
  • 确保您的应用继续在后台运行。您可以使用ol'[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler]如果你愿意,但我认为还有更好的方法。

  • 播放实际音频(请注意,我使用的是 ARC,这就是没有 release 调用的原因):

    NSURL * file = [[NSBundle mainBundle] URLForResource:@"beep" withExtension:@"aif"];    
    AVURLAsset * asset = [[AVURLAsset alloc] initWithURL:file options:nil];
    AVPlayerItem * item = [[AVPlayerItem alloc] initWithAsset:asset];
    __block AVPlayer * player = [[AVPlayer alloc]initWithPlayerItem:item];
    __block id finishObserver = [[NSNotificationCenter defaultCenter] addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
    object:player.currentItem
    queue:[NSOperationQueue mainQueue]
    usingBlock:^(NSNotification *note) {
    [[NSNotificationCenter defaultCenter] removeObserver:finishObserver];

    // Reference the 'player' variable so ARC doesn't release it until it's
    // finished playing.
    player = nil;
    }];

    // Trigger asynchronous load
    [asset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:@"tracks"] completionHandler:^{
    // Start playing the beep (watch out - we're not on the main thread here)!
    [player play];
    }];
  • 这太棒了!

关于iphone - 在 iPhone 上播放背景音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/907965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com