【问题标题】:How to connect the audio to bluetooth when playing using AVPlayer使用 AVPlayer 播放时如何将音频连接到蓝牙
【发布时间】:2015-09-16 23:25:51
【问题描述】:

我正在使用 AVPlayer 播放来自 url 的音频,但是当 iPhone 连接到蓝牙设备时,它没有通过蓝牙播放,如果连接了如何通过蓝牙播放,我在 SO 中看到了一些帖子,但没有其中有明确的解释。下面是我的代码。

    -(void)playselectedsong{

    AVPlayer *player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:urlString]];
    self.songPlayer = player;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:[songPlayer currentItem]];
    [self.songPlayer addObserver:self forKeyPath:@"status" options:0 context:nil];
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProgress:) userInfo:nil repeats:YES];

    [self.songPlayer play];

}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if (object == songPlayer && [keyPath isEqualToString:@"status"]) {
        if (songPlayer.status == AVPlayerStatusFailed) {
            NSLog(@"AVPlayer Failed");

        } else if (songPlayer.status == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");


        } else if (songPlayer.status == AVPlayerItemStatusUnknown) {
            NSLog(@"AVPlayer Unknown");

        }
    }
}

- (void)playerItemDidReachEnd:(NSNotification *)notification {

 //  code here to play next sound file

}

【问题讨论】:

  • 您的意思是根本不通过蓝牙播放,还是在播放歌曲时从扬声器切换到蓝牙时不通过蓝牙播放?
  • @MDB983:它根本不是通过蓝牙播放的。
  • @MDB983:关于这个问题的任何想法,请帮助我。
  • 我找到了这篇文章。它可能对你有帮助。 stackoverflow.com/questions/17482608/…

标签: ios iphone bluetooth avaudioplayer avplayer


【解决方案1】:

试试这个

UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
                         sizeof(sessionCategory),&sessionCategory);

// Set AudioSession
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:&sessionError];

UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryEnableBluetoothInput, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);

【讨论】:

  • @PoojaSrivastava 在此文件“AppDelegate.m”的此方法“didFinishLaunchingWithOptions”中编写此代码。注意:- 在这一行“[self.window makeKeyAndVisible];”之前写下这段代码。
  • "只有当音频会话类别为 AVAudioSessionCategoryPlayAndRecord 或 AVAudioSessionCategoryRecord 时,您才能设置 AVAudioSessionCategoryOptionAllowBluetooth 选项。"来源:developer.apple.com/documentation/avfoundation/…
【解决方案2】:

对于 Swift 3.1

短版:

let audioSession = AVAudioSession.sharedInstance()
do {
    try audioSession.setCategory(AVAudioSessionCategoryRecord, with: [.allowBluetooth])
    try audioSession.setActive(true)
} catch {
    fatalError("Error Setting Up Audio Session")
}

确保您使用正确输入的扩展版本:

/**
    Check availability of recording and setups audio session
    with prioritized input.
 */
func setupSessionForRecording() {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryRecord, with: [.allowBluetooth])
    } catch {
        fatalError("Error Setting Up Audio Session")
    }
    var inputsPriority: [(type: String, input: AVAudioSessionPortDescription?)] = [
        (AVAudioSessionPortLineIn, nil),
        (AVAudioSessionPortHeadsetMic, nil),
        (AVAudioSessionPortBluetoothHFP, nil),
        (AVAudioSessionPortUSBAudio, nil),
        (AVAudioSessionPortCarAudio, nil),
        (AVAudioSessionPortBuiltInMic, nil),
    ]
    for availableInput in audioSession.availableInputs! {
        guard let index = inputsPriority.index(where: { $0.type == availableInput.portType }) else { continue }
        inputsPriority[index].input = availableInput
    }
    guard let input = inputsPriority.filter({ $0.input != nil }).first?.input else {
        fatalError("No Available Ports For Recording")
    }
    do {
        try audioSession.setPreferredInput(input)
        try audioSession.setActive(true)
    } catch {
        fatalError("Error Setting Up Audio Session")
    }
}

/**
    Check availability of playing audio and setups audio session
    with mixing audio.
 */
func setupSessionForPlaying() {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryPlayback, with: [.mixWithOthers])
        try audioSession.setActive(true)
    } catch {
        fatalError("Error Setting Up Audio Session")
    }
}

主要思想是您有 2 个函数来更改音频会话设置。在录音前使用setupSessionForRecording,在播放音频前使用setupSessionForPlaying

重要使用AVAudioSessionCategoryRecordAVAudioSessionCategoryPlayback,而不是AVAudioSessionCategoryPlayAndRecord,因为它有问题。仅当您确实需要同时播放和录制音频时才使用AVAudioSessionCategoryPlayAndRecord

【讨论】:

  • 尝试了上面的代码并在网上寻找了几乎所有的解决方案。一切都设置正确。但是蓝牙耳机输入/输出只是没有被应用程序占用。当输入成功设置为 bluetoothHFP 时,手机麦克风也会停止,但是当您说话时,它不会接听。有线耳机虽然工作完美。同样的蓝牙耳机与 Siri 完美配合。我是否缺少其他一些配置设置 - 例如权限或功能?使用设备:iphone 5c (10.3.2)
  • @SayaleePote 您是否尝试将 AV 类别设置为 AVAudioSessionCategoryPlayAndRecord
  • 是的,它之前设置为 PlayAndRecord。没用。然后我按照这里的建议单独设置它。还是没有成功。
【解决方案3】:

您需要在AVAudioSession 上设置类别和选项。

在应用启动时试试这个:

//configure audio session
NSError *setCategoryError = nil;
BOOL setCategorySuccess = [[AVAudioSession sharedInstance]
                           setCategory:AVAudioSessionCategoryPlayback
                           withOptions:AVAudioSessionCategoryOptionAllowBluetooth
                           error:&setCategoryError];

if (setCategorySuccess) {
    NSLog(@"Audio Session options set.");
} else {
    NSLog(@"WARNING: Could not set audio session options.");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    相关资源
    最近更新 更多