如何在xcode中的应用程序中播放声音后重新启动音乐播放器

时间:2014-01-18 10:13:07

标签: ios objective-c xcode avaudioplayer

在播放我的声音时使用AVAudioPlayer停止播放背景中的音乐播放器,当我的声音结束时音乐播放器不能恢复时,我该如何恢复音乐播放器?

1 个答案:

答案 0 :(得分:1)

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

@interface ViewController () <AVAudioPlayerDelegate>

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"ttt" ofType:@"mp3"]] error:nil];
_audioPlayer.delegate = self;
}

- (void)play:(id)sender
{
    [_audioPlayer play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error = nil;
    if (![audioSession setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error]) {
        NSLog(@"resume music player failed, error=%@", error);
    }
}

@end