简体   繁体   English

当其他应用程序在Swift中播放音乐时,将我的应用程序静音

[英]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.

相关问题 我的应用启动后,其他应用的音乐停止播放 - Music from other apps stops playing when my app starts 从我的应用程序内部控制其他应用音乐播放? - Control other apps music playing from inside my app? 应用程序在后台Swift Xcode不能播放音乐 - Music not playing when app is in the background Swift Xcode 当我的Android应用正在播放音乐时,如何关闭所有其他音乐? - How to turn off all other music when my Android app is playing music? 在我的应用内控制其他应用的音乐 - Control music of other apps within my app 当其他音频开始在同一个应用程序中播放时,将AVPlayer静音 - Mute AVPlayer when other audio starts playing in the same app 如果另一个应用程序中的音乐正在spritekit中播放,如何使AVAudioPlayer静音 - How to mute AVAudioPlayer if music from another app is playing in spritekit 在 Swift 中使用属性 canPlayReverse 时,为什么我的音乐没有反向播放? - Why is my music not playing in reverse when using the property canPlayReverse in Swift? 仅当视频在我的应用 Swift UIKit 中取消静音时才停止其他应用的背景音乐 - stop background music of other app only when the video is unmuted in my app Swift UIKit 苹果背景音乐/ Spotify在后台播放时暂停的快速背景音乐 - Swift background music that pauses when apple music/ spotify is playing in background
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM