问题 使用AVPlayer播放时如何将音频连接到蓝牙


我正在使用AVPlayer从网址播放音频,但是当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

}

9010
2018-06-30 08:48


起源

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


答案:


尝试这个

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);

4
2017-07-06 09:50



在哪里写这段代码 - Pooja Srivastava
@PoojaSrivastava在此文件“AppDelegate.m”的此方法“didFinishLaunchingWithOptions”中编写此代码。注意: - 在此行“[self.window makeKeyAndVisible];”之前写下此代码。 - Pramod


对于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 在播放音频之前。

重要 使用 AVAudioSessionCategoryRecord 和 AVAudioSessionCategoryPlayback, 但不是 AVAudioSessionCategoryPlayAndRecord,因为它的马车。使用 AVAudioSessionCategoryPlayAndRecord 只有你真的需要同时播放和录制音频。


3
2018-05-29 16:59



尝试了上面的代码,并在线寻找几乎所有的解决方案。一切都设置正确。但蓝牙耳机输入/输出只是应用程序没有采取。当输入成功设置为bluetoothHFP时,手机麦克风也会停止,但是当你说话时,它不能捕捉到。有线耳机虽然工作得很好。相同的蓝牙耳机与Siri完美配合。是否有其他一些我缺少的配置设置 - 如权限或功能?使用的设备:iphone 5c(10.3.2) - Sayalee Pote
@SayaleePote您是否尝试将AV类别设置为 AVAudioSessionCategoryPlayAndRecord? - Vasilii Muravev
是的,它之前已设置为PlayAndRecord。没工作。然后我按照此处的建议单独设置它。仍然没有成功。 - Sayalee Pote


您需要在上面设置类别和选项 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.");
}

2
2017-07-04 13:38