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

时间:2015-06-30 08:48:03

标签: ios iphone bluetooth avaudioplayer 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

}

3 个答案:

答案 0 :(得分:5)

试试这个

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

答案 1 :(得分:4)

适用于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")
    }
}

您有两个功能可以更改音频会话设置。在录制前使用setupSessionForRecording,在播放音频前使用setupSessionForPlaying

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

答案 2 :(得分:2)

您需要在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.");
}