2015-06-30 6 views
11

Ich spiele Audio von einer URL mit AVPlayer, aber wenn das iPhone mit einem Bluetooth-Gerät verbunden ist, spielt es nicht über Bluetooth, wie über Bluetooth, wenn es ist verbunden, ich sehe einige Beiträge in SO, aber keine davon wird klar erklärt. Unten ist mein Code.Wie verbinde ich Audio mit Bluetooth bei der Wiedergabe mit 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

Meinst du, es wird überhaupt nicht über Bluetooth wiedergegeben, oder es wird nicht über Bluetooth abgespielt, wenn du während der Wiedergabe vom Lautsprecher auf Bluetooth umspringst? – MDB983

+0

@ MDB983: Es spielt überhaupt nicht über Bluetooth. –

+0

@ MDB983: Irgendeine Idee zu dem Thema, bitte helfen Sie mir aus. –

Antwort

4

Versuchen Sie, diese

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

wo schreiben Sie diesen Code –

+0

@ PoojaSrivastava schreiben Sie diesen Code in dieser Methode "didFinishLaunchingWithOptions" dieser Datei " AppDelegate.m ". Hinweis: - Schreiben Sie diesen Code vor dieser Zeile "[self.window makeKeyAndVisible]; ". – Pramod

2

Sie müssen eine Kategorie und Optionen auf dem AVAudioSession setzen.

die Sie interessieren, wenn die Anwendung gestartet wird:

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

Für Swift 3.1

Kurzversion:

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

Erweitert Version sicher sein, dass Sie die richtigen Eingang verwenden:

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

Die Hauptidee, die Sie 2 Funktionen zum Ändern Audio-Session-Einstellungen. Verwenden Sie setupSessionForRecording direkt vor der Aufnahme und setupSessionForPlaying vor dem Abspielen von Audio.

WichtigeAVAudioSessionCategoryRecord und AVAudioSessionCategoryPlayback, zu verwenden, aber nicht AVAudioSessionCategoryPlayAndRecord, weil es Buggy ist. Verwenden Sie AVAudioSessionCategoryPlayAndRecord nur, wenn Sie wirklich gleichzeitig Audio abspielen und aufnehmen müssen.

+0

versuchte den oben genannten Code und suchte nach fast jeder Lösung online. Alles ist richtig eingestellt. Aber die Bluetooth-Headset-Ein-/Ausgabe wird gerade nicht von der App übernommen. Das Telefonmikrofon stoppt auch, wenn der Eingang erfolgreich auf Bluetooth HFP gestellt wird, aber wenn Sie sprechen, fängt es nicht an. kabelgebundene Headsets funktionieren perfekt. Das gleiche Bluetooth Headset funktioniert perfekt mit Siri. Gibt es eine andere Konfigurationseinstellung, die ich vermisse - wie Berechtigungen oder Funktionen? Verwendete Vorrichtung: iphone 5c (10.3.2) –

+0

@SayaleePote Haben Sie versucht, die AV-Kategorie auf 'AVAudioSessionCategoryPlayAndRecord' zu setzen? –

+0

Ja, es wurde früher auf PlayAndRecord eingestellt. Hat nicht funktioniert. Dann stelle ich es separat wie hier vorgeschlagen. Immer noch kein Erfolg. –

Verwandte Themen