2015-06-30 18 views
11

Tôi đang phát âm thanh từ url bằng AVPlayer, nhưng khi iPhone được kết nối với thiết bị Bluetooth, nó không phát qua Bluetooth, cách phát qua Bluetooth nếu nó kết nối, tôi thấy một số bài viết trong SO, nhưng không ai trong số đó được giải thích rõ ràng. Dưới đây là mã của tôi.Cách kết nối âm thanh với bluetooth khi phát bằng AVPlayer

-(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 

} 
+0

Bạn có nghĩa là nó không phát qua Bluetooth chút nào hoặc nó không phát qua Bluetooth khi bạn chuyển từ loa sang Bluetooth trong khi đang phát bài hát? – MDB983

+0

@ MDB983: Không phát qua Bluetooth. –

+0

@ MDB983: Bất kỳ ý tưởng nào về vấn đề này, hãy giúp tôi. –

Trả lời

4

Hãy thử điều này

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

nơi viết mã này –

+0

@PoojaSrivastava viết mã này theo phương thức "didFinishLaunchingWithOptions" của tệp này " AppDelegate.m ". lưu ý: - viết mã này trước dòng này "[self.window makeKeyAndVisible]; ". – Pramod

2

Bạn cần đặt danh mục và tùy chọn trên AVAudioSession.

Hãy thử điều này khi ứng dụng bắt đầu:

//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

Đối Swift 3,1

phiên bản ngắn:

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

Phiên bản mở rộng để đảm bảo rằng bạn đang sử dụng đúng đầu vào:

/** 
    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") 
    } 
} 

Ý tưởng chính là bạn có 2 chức năng để thay đổi cài đặt phiên âm thanh. Sử dụng setupSessionForRecording ngay trước khi ghi và setupSessionForPlaying trước khi phát âm thanh.

quan trọng sử dụng AVAudioSessionCategoryRecordAVAudioSessionCategoryPlayback, nhưng không AVAudioSessionCategoryPlayAndRecord, vì đó là lỗi. Chỉ sử dụng AVAudioSessionCategoryPlayAndRecord nếu bạn thực sự cần phát và ghi âm cùng một lúc.

+0

Đã thử mã trên và tìm kiếm hầu hết mọi giải pháp trực tuyến. Mọi thứ được đặt chính xác. Nhưng đầu vào/đầu ra tai nghe bluetooth chỉ không được ứng dụng thực hiện. Micrô điện thoại cũng dừng khi đầu vào được đặt thành công thành bluetoothHFP, nhưng khi bạn nói, nó không bị bắt. tai nghe có dây hoạt động hoàn hảo mặc dù. Tai nghe bluetooth tương tự hoạt động hoàn hảo với Siri. Có một số cài đặt cấu hình khác mà tôi bị thiếu - như quyền hoặc khả năng không? Thiết bị được sử dụng: iphone 5c (10.3.2) –

+0

@SayaleePote Bạn đã cố gắng đặt danh mục AV thành 'AVAudioSessionCategoryPlayAndRecord' chưa? –

+0

Có nó đã được đặt thành PlayAndRecord trước đó. Không làm việc. Sau đó, tôi đặt nó một cách riêng biệt như đề nghị ở đây. Vẫn không thành công. –

Các vấn đề liên quan