[英]Mute My App When Other Apps are Playing Music in Swift
I'm writing an app that plays music. 我正在编写一个播放音乐的应用程序。 However, I'd like to make it so that my app's music pauses when other music is playing, such as music from iTunes. 但是,我希望这样做,以便在播放其他音乐(例如iTunes中的音乐)时暂停我的应用程序的音乐。 How would I accomplish this? 我将如何完成? Here's my code: 这是我的代码:
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ambler", ofType: "mp3")!)
// Removed deprecated use of AVAudioSessionDelegate protocol
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
audioPlayer.numberOfLoops = -1
To do this I believe you are going to need to check if the music player is playing, here is how I would do that in Objective-C. 为此,我相信您需要检查音乐播放器是否正在播放,这是我在Objective-C中的处理方法。
First #import <MediaPlayer/MediaPlayer.h>
and add the library to your build phases. 首先#import <MediaPlayer/MediaPlayer.h>
并将库添加到构建阶段。
- (BOOL)isPlaying
{
MPMusicPlayerController *musicPlayer = [MPMusicPlayerController systemMusicPlayer];
if (musicPlayer.playbackState == MPMusicPlaybackStatePlaying) {
return YES;
}
return NO;
}
When initializing musicPlayer
it may cause the music to stop, if so I would look into 初始化musicPlayer
它可能会导致音乐停止播放,如果这样的话,我会调查一下
+ (MPMusicPlayerController *)applicationMusicPlayer
Swift 迅速
func isPlaying() -> Bool {
let musicPlayer = MPMusicPlayerController.systemMusicPlayer()
if musicPlayer.playbackState == MPMusicPlaybackState.Playing {
return true
}
return false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.