在应用程序中阻止音乐停止

时间:2016-03-07 19:27:10

标签: ios xcode swift

我正在使用StackOverflow中的这个pod:https://github.com/piemonte/Player

但我有一个问题。当用播放器打开视图时,来自股票音乐应用程序的音乐停止播放。我怎么能让它不停止呢?

这是玩家代码:

self.player = Player()
self.player.delegate = self
player.view.frame.size.width = UIScreen.mainScreen().bounds.size.width

player.view.frame.size.height = player.view.frame.size.width

player.fillMode = AVLayerVideoGravityResizeAspectFill
player.view.sizeToFit()
videoCell!.addSubview(player.view)

let videoUrl: NSURL = fileUrl!
self.player.setUrl(videoUrl)
self.player.playFromBeginning()

self.player.playbackLoops = true

let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:"handleTapGestureRecognizer:")
tapGestureRecognizer.numberOfTapsRequired = 1
self.player.view.addGestureRecognizer(tapGestureRecognizer)

1 个答案:

答案 0 :(得分:0)

把它放在appDelegate中,希望这会有所帮助:)

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

- (BOOL)application:(UIApplication *)application
willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

 AVAudioSession *audioSession = [AVAudioSession sharedInstance];

 NSError *setCategoryError = nil;
 BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
 if (!success) { /* handle the error condition */ }

 NSError *activationError = nil;
 success = [audioSession setActive:YES error:&activationError];
 if (!success) { /* handle the error condition */ } 

}

Swift版

var audioPlayer = AVAudioPlayer()

func playAudio() {
    do {
        if let bundle = NSBundle.mainBundle().pathForResource("Flip 02", ofType: "wav") {
            let alertSound = NSURL(fileURLWithPath: bundle)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        }
    } catch {
        print(error)
    }
}