AVAudioSessionCategoryAmbient听起来没有耳机乱码

时间:2015-02-04 09:56:41

标签: ios objective-c xcode avplayer avaudiosession

我尝试在我的应用上播放声音,同时播放其他应用音乐,例如Spotify。 随着AVAudioSessionCategoryAmbient spotify音乐继续播放,但我的应用听起来声音乱码,但如果我使用耳机听起来不错。

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];

此外,我已经尝试过此代码,但它会停止其他应用音乐。

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error: nil];

我的代码MHSoundPlayerController.m:

#import <AVFoundation/AVFoundation.h>
#import "MHSoundPlayerController.h"

@interface MHSoundPlayerController ()
@property  (nonatomic, strong) AVPlayer *player;
@end

@implementation MHSoundPlayerController

+ (id)sharedInstance
{
    static dispatch_once_t pred;
    static MHSoundPlayerController *shared = nil;
    dispatch_once(&pred, ^{
        shared = [[MHSoundPlayerController alloc] init];
    });
    return shared;
}

- (void)playSound:(NSString*)sound
{
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error: nil];
    if (self.player) {
        [self.player removeObserver:self forKeyPath:@"status" context:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        self.player = nil;
    }
    NSString *path = [[NSBundle mainBundle] pathForResource:sound ofType:@"wav"];
    NSURL *url = [[NSURL alloc] initFileURLWithPath: path];
    self.player = [AVPlayer playerWithURL:url];
    [self.player addObserver:self forKeyPath:@"status" options:0 context:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.player && [keyPath isEqualToString:@"status"]) {
        if (self.player.status == AVPlayerStatusFailed) {
            NSLog(@"AVPlayer Failed");
        }
        else if (self.player.status == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            [self.player play];
        }
        else if (self.player.status == AVPlayerItemStatusUnknown) {
            NSLog(@"AVPlayer Unknown");
        }
    }
}

- (void)playerItemDidReachEnd:(NSNotification *)notification
{
    //Endid playing
}


@end

0 个答案:

没有答案