2

AVAudioPlayer を使用して、iPhone プレーヤーの再生中にサウンドを再生しようとしています。また、デバイスがロックされている場合。問題は、iPhone 4s ios 7 では正常に動作することです。しかし、6 および 7 ios を搭載した iPhone 5 では何も起こりません。

私が書いた-Info.plist中でRequired background modes

App plays audio or streams audio/video using AirPlay

Player.h実装中:

@property (nonatomic, strong) AVAudioPlayer *notificationPlayer;

<AVAudioPlayerDelegate, AVAudioSessionDelegate>#import <AVFoundation/AVFoundation.h>付属_

また、Player.m

//this is called on viewDidLoad
-(void) prepareSound{
    [[AVAudioSession sharedInstance] setDelegate:self];
}
//overriden function
- (void)playAudio:(NSString *)path{
    [[AVAudioSession sharedInstance]
     setCategory: AVAudioSessionCategoryAmbient
     withOptions: AVAudioSessionCategoryOptionDuckOthers
     error: nil];

    NSError *error;
    NSURL *audioURL = [NSURL fileURLWithPath:path];

    self.notificationPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:audioURL error:&error];
    self.notificationPlayer.delegate = self;
    [self.notificationPlayer prepareToPlay];
    [self.notificationPlayer setVolume:1.0];
    [self.notificationPlayer play];
    if (error) {
        NSLog(@"error %@",[error localizedDescription]);
    }
}

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [player stop]; 
    [[AVAudioSession sharedInstance] setActive:NO withOptions:0 error:nil];
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient
                                     withOptions: 0
                                           error: nil];
    [[AVAudioSession sharedInstance] setActive:YES withOptions: 0 error:nil];
}
//Call from here
-(void) customMethod{
    [self playAudio:[[NSBundle mainBundle] pathForResource:@"3" ofType:@"wav"]];
}

よろしく。

4

2 に答える 2

1

次のコードを使用する必要があります

- (void)playAudio:(NSString *)path {
NSError *error;
NSURL *audioURL = [NSURL fileURLWithPath:path];

self.notificationPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:audioURL error:&error];
self.notificationPlayer.delegate = self;

AVAudioSession* audioSession = [AVAudioSession sharedInstance];
NSError *errorSession = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil];
[audioSession setActive:NO error:&errorSession];

[self.notificationPlayer prepareToPlay];
[self.notificationPlayer setVolume:1.0];
[self.notificationPlayer play];
if (error) {
    NSLog(@"error %@",[error localizedDescription]);
}
NSLog(@"Should play music");
}

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[player stop];
[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
}
于 2013-10-26T13:27:48.460 に答える