How to let background music continue? - ios

I want to allow a player to use their music in my game, so I want to know how to detect if the player is playing music from his music library so I can let his music continue playing and if not let my music play in the background.
I use this code to play music in my GameViewController:
let bgMusicURL: NSURL = NSBundle.mainBundle().URLForResource("Squart-GameMusic", withExtension: "wav")!
do {
Data.GameMusic = try AVAudioPlayer(contentsOfURL: bgMusicURL, fileTypeHint: nil)
} catch {
return print("no music file")
}
Data.GameMusic.numberOfLoops = 1
Data.GameMusic.prepareToPlay()
Data.GameMusic.play()
The problem is that when I try to play music from Music Library the sound stops and it lets my app play music instead of the Music Library.

Check whether the music is playing or not in the background like this
if MPMusicPlayerController.systemMusicPlayer().playbackState == .Playing {
print("Music is playing")
} else {
print("Play your music")
}
Don't forget to import:
import MediaPlayer
And if you want to play the sound simultaneously then use this code to play the sound file
func playSound {
var soundID: SystemSoundID = 0
let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "myFileName", "mp3", nil)
AudioServicesCreateSystemSoundID(soundURL, &soundID)
AudioServicesPlaySystemSound(soundID)
}

Related

How to stop audio of Music App while playing audio from my app?

I am facing one issue is :-
If audio of Music Application is playing and I will open my app that time both the audio are playing parallel.
I want to stop music of Music App and want to continue my app audio.
That is happening in if I will go to inactive state (play music from music app) to active state of app.
I am initialising the AVAudioPlayer :-
func setAudioSession(){
// Set Audio session
self.audioPlayer.delegate = self
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
}
catch {
print("AVAudioSession error")
}
}
func startPlayer(at index: Int) {
do {
self.playingItem = self.queueArray[index]
self.player = try AVAudioPlayer(contentsOf: fileURL)
self.player?.currentTime = beginTime
self.player?.delegate = self
self.player?.prepareToPlay()
self.player?.play()
}
catch {
debugPrint(error.localizedDescription)
}
}
How I can stop music of Music App and want to continue my app audio
?

Swift background music that pauses when apple music/ spotify is playing in background

I want my background song to stop playing when music from another app is playing. Such as apple music or Spotify. If you download color switch you'll know what I mean. Currently Im using the method below but my background song doesn't stop it mixes with the playing music.(This method kinda works with apple music but not Spotify). I want my song to play indefinitely until other music is playing in background and for it to start again when the other music is paused.(Try it with color Switch)
Thanks
func setUpAudio() {
//dead = SKAction.playSoundFileNamed(SoundFile.dead, waitForCompletion: true)
// buttonpress = SKAction.playSoundFileNamed(SoundFile.button, waitForCompletion: true)
if GameScene.backgroundMusicPlayer == nil {
let backgroundMusicURL = Bundle.main.url(forResource: SoundFile.BackgroundMusic, withExtension: nil)
do {
let theme = try AVAudioPlayer(contentsOf: backgroundMusicURL!)
GameScene.backgroundMusicPlayer = theme
} catch {
// couldn't load file :[
}
GameScene.backgroundMusicPlayer.numberOfLoops = -1
}
if !GameScene.backgroundMusicPlayer.isPlaying {
GameScene.backgroundMusicPlayer.play()
}
let audioSession = AVAudioSession.sharedInstance()
/*try!audioSession.setCategory(AVAudioSessionCategoryAmbient, with: AVAudioSessionCategoryOptions.mixWithOthers
)*/
do { try!audioSession.setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true) }
catch let error as NSError { print(error) }
//s audio from other sessions to be ducked (reduced in volume) while audio from this session plays
}
You're session category allows mixing, which is not what you want. Try using AVAudioSessionCategoryPlayback or AVAudioSessionCategorySoloAmbient, as these won't allow your app to mix audio with other apps.
See the docs for more info
You will need to set the AVAudioSession to active.
let _ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
let _ = try? AVAudioSession.sharedInstance().setActive(true)

iOS: audio files used in app sound harsher than when played outside the app

The audio files for our iOS app sound much worse when played through the app than when played outside the app. The sounds seem harsher and more "ecohy".
Here's our code for playing audio. Are we somehow altering the playback or natural sound of the audio?
Two of the audio files we're using can be found here:
private func createAudioPlayer(filename: String) -> AVAudioPlayer {
// Define file URL
let path = Bundle.main.path(forResource: filename, ofType: nil)
let url = URL(fileURLWithPath: path!)
// Create player
let audioPlayer: AVAudioPlayer!
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
} catch {
audioPlayer = nil
printError("Error creating audio player for \(url): \(error)")
logEvent("Audio Error", userData: nil)
}
// Print status
print("Created audio player for \(filename)")
// Return player
return audioPlayer
}
func play(file: AudioFileEnum) {
if let player = audioPlayers[file] {
if player.isPlaying {
player.pause()
}
player.currentTime = 0
player.play()
} else {
printError("Error finding audio player for \(file)")
}
}
Have you tried setting the volume on the audioPlayer object to something smaller, like 0.05f, and adjusting from there?

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. 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.
First #import <MediaPlayer/MediaPlayer.h> and add the library to your build phases.
- (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
+ (MPMusicPlayerController *)applicationMusicPlayer
Swift
func isPlaying() -> Bool {
let musicPlayer = MPMusicPlayerController.systemMusicPlayer()
if musicPlayer.playbackState == MPMusicPlaybackState.Playing {
return true
}
return false
}

Swift - Music from in app to system on button click

At the moment I have a check in my app to see if iTunes is playing, and if it is, to proceed with iTunes music and not play the in game music. If iTunes is not playing anything, then to play the in game music.
I am trying to incorporate this into 2 functions and have a button that switches between:
Play iTunes rather in game music
Play in game music rather iTunes
This is currently in my viewDidLoad()
let check = isPlaying()
let path = NSBundle.mainBundle().pathForResource("music.mp3", ofType: nil)!
let url = NSURL(fileURLWithPath: path)
do {
if check == false {
let sound = try AVAudioPlayer(contentsOfURL: url)
music = sound
sound.play()
}
} catch { }
The isPlaying() function
func isPlaying() -> Bool {
let musicPlayer = MPMusicPlayerController.systemMusicPlayer()
if musicPlayer.playbackState == MPMusicPlaybackState.Playing {
ingame = false;
return true
}
return false
}
I tried to incorporate the previous code into a function that will be triggered by a button:
func playInGameMusic() {
let path = NSBundle.mainBundle().pathForResource("music.mp3", ofType: nil)!
let url = NSURL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOfURL: url)
music = sound
sound.play()
ingame = true
} catch { }
}
However, I have no idea how to go about my playSystemMusic() function. Is there a way to resume iTunes from within my app? I understand their is an MPMusicPlayerController class, but I am not sure what I am supposed to use to make iTunes play from a button within my app.
Any guidance is appreciated, thanks.

Resources