使用AVPlayer播放时如何将音频连接到蓝牙 [英] How to connect the audio to bluetooth when playing using AVPlayer

查看:238
本文介绍了使用AVPlayer播放时如何将音频连接到蓝牙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AVPlayer从网址播放音频,但是当iPhone连接到蓝牙设备时,它不能通过蓝牙播放,如果连接后如何通过蓝牙播放,我看到SO中的一些帖子,但没有这些都清楚地解释了。下面是我的代码。

I am playing the audio from an url using AVPlayer, but when the iPhone is connected to a Bluetooth device it is not playing via Bluetooth, how to play via Bluetooth if it is connected, i see some posts in SO, but none of those are clearly explained. Below is my code.

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

}


推荐答案

试试这个

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

这篇关于使用AVPlayer播放时如何将音频连接到蓝牙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆