How do I switch background music using AVFoundation in Xcode?

Asked 2 years ago, Updated 2 years ago, 44 views

Currently, I am studying with a sample application for omikuji.
I was able to play BGM by referring to the sample code, but I don't know how to switch BGM.
I would like to switch background music without using the screen transition.

What kind of cord should I put in which part to switch the background music?

If anyone understands, I would appreciate it if you could teach me.
My environment is Xcode7swift2.0.

- Play GameViewController BGM1 -

import UIKit
import SpriteKit
Import the import AVFoundation // AVFoundation framework.

classGameViewController:UIViewController {

    var player —Variables for controlling AVAudioPlayer?//BGM
    var soundManager=SEManager() // Variables instantiated in SEManager
    // BGM playback method
    funcplay(soundName:String) {
        // Load sound file
        let soundPath=NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent(soundName)
        // Pass the loaded file
        let url —NSURL?=NSURL.fileURLWithPath(soundPath)
        do{
            // Set the path to the mp3 file loaded into ↓player
            player=try AVAudioPlayer(contentsOfURL:url!)
        } catch_{
            player=nil
        }
        player?.numberOfLoops=-1// Loop BGM indefinitely
        player?prepareToPlay()// Immediately play audio.
        player?play()//Play sound
    }


    override func viewDidLoad(){
        super.viewDidLoad()

        //bgm
        // Do any additional setup after loading the view, typically from anib.
        Calling the //play method.The argument is the filename.
        play("bgm1.mp3")


        let screen = GameScene (size: CGSize (width: 750, height: 1334))
        let skView=self.view as!SKView
        scene.scaleMode=.AspectFit
        skView.presentScene(scene)
    }

    override func shouldAutorotate()->Bool{
        return true
    }

    override func supportedInterfaceOrients()->UIInterfaceOrientationMask{
        if UIDevice.currentDevice().userInterfaceIdiom==.Phone {
            return UIInterfaceOrientationMask.AllButUpsideDown
        } else{
            return UIInterfaceOrientationMask.All
        }
    }

    override funcdidReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
        // Release any cached data, images, etc that aren't in use.
    }

    override funcprefersStatusBarHidden() - >Bool{
        return true
    }
}

...GameScene.swift

import SpriteKit
import AVFoundation

classGameScene:SKScene{
    // prepare a sprite for illustration
    let mySprite=SKSpriteNode(imageNamed: "omikuji.png")
    // prepare a sprite for buttons
    let btnSprite=SKSpriteNode(imageNamed: "button.png")
    // prepare labels for omikuji results
    let myLabel=SKLabelNode(fontNamed: "Verdana-bold")

    override func DidMoveToView (view:SKView) {



        // color the background
        self.backgroundColor=SKColor.whiteColor()
        // display an illustration
        mySprite.position=CGPoint (x:375, y:900)
        addChild (mySprite)
        // display a button
        btnSprite.position = CGPoint (x:375, y:200)
        self.addChild(btnSprite)
        // display omikuji result labels
        myLabel.text="???"
        myLabel.fontSize=65
        myLabel.fontColor=SKColor.blackColor()
        myLabel.position=CGPoint (x:375, y:500)
        self.addChild(myLabel)
    }
    // Touch Action
    override functouchesBegan(touches:Set<UITouch>, withEvent:UIEvent?) {
        for touch:AnyObject into touches {
            // Look at what's in the touched position.
            let location = touch.locationInNode(self)
            let touchNode=self.nodeAtPoint(location)
            // If it's a button,
            iftouchNode==btnSprite{

                // BGM does not stop when sound effects occur


                // the creation of sound effects data
                let mySoundAction: SKAction=SKAction.playSoundFileNamed("hit.wav", waitForCompletion:true")
                // playback action
                self.runAction (mySoundAction);

                // Mark ??? and then wag the omikuji
                myLabel.text="???"
                shakeOmikuji()
            }
        }
    }
    // omikuji-shaking process
    func shakeOmikuji(){

        // BGM sample 1 stopped playing
        // Now I want to switch background music to sample 2


        // [Turn on the action of wielding omikuji]
        // the action of tilting the omikuji slightly to the right
        let action1 = SKAction.rotateToAngle (-0.3, duration: 0.2)
        // the action of tilting the omikuji slightly to the left
        let action 2 = SKAction.rotateToAngle (0.3, duration: 0.2)
        // the action of turning over a lottery ticket
        let action 3 = SKAction.rotateToAngle (3.14, duration: 0.2)
        // Action 1, action 2, action 3 in the order specified
        let actionS = SKAction.sequence(
            [action1, action2, action1, action2, action1, action3])

        // Add an action to the omikuji and run kekka at the end.
        mySprite.runAction(actionS, completion:showOmikuji)
    }
    // The process of displaying results
    func showOmikuji(){
        varomikuji = ["Okichi", "Nakayoshi", "Kichi", "Kichi"]
        letter=Int(arc4 random_uniform(4))
        myLabel.text=omikuji[r]
    }

    override func update (currentTime:CFTimeInterval) {
    }
}

swift

2022-09-30 20:51

2 Answers

How do you want to change the background music?
This will change the code you add.
For example, the background music is changed by tapping the button.and so on.
If you simply want to change your music, you can change it by stopping AVAudioPlayer, passing it again, and doing prepareToPlay().


2022-09-30 20:51

Below is a program that changes the BGM by tapping one finger, and stops or resumes playing BGM by tapping two fingers (or more).

import UIKit
import SpriteKit
import AVFoundation

classGameScene:SKScene{

    private var southernURL —NSURL!
    private var happyURL —NSURL!
    varcurrentBGM:AVAudioPlayer!

    override init (size: CGSize) {
        super.init (size:size)

        self.backgroundColor=UIColor.yellowColor()
    }

    required init?(coder adecoder:NSCoder) {
        fatalError("init(coder:)has not been implemented")
    }

    override func DidMoveToView (view:SKView) {
        super.didMoveToView(view)

        let bndl = NSBundle.mainBundle()
        southernURL=bndl.URLForResource("southern", withExtension:"m4a")
        happyURL=bndl.URLForResource("happy", withExtension:"m4a")

        currentBGM = AVAudioPlayer (contentsOfURL:southernURL, error:nil)
        currentBGM.numberOfLoops=-1
        currentBGM.play()
    }

    override func willMoveFromView (view:SKView) {
        super.willMoveFromView(view)

        if currentBGM.playing == true {
            currentBGM.stop()
        }
    }

    override functouchesBegan (touches:Set<NSObject>, withEvent:UIEvent) {
        if touches.count<2 {// single finger tap,
            changeBGM()
        } else {// If you have more than two fingers,
            pauseBGM()
        }
    }

    US>func changeBGM(){
        if currentBGM.playing {
            currentBGM.stop()
            if currentBGM.url==southernURL{
                currentBGM=AVAudioPlayer(contentsOfURL:happyURL, error:nil)
            } else{
                currentBGM = AVAudioPlayer (contentsOfURL:southernURL, error:nil)
            }
            currentBGM.numberOfLoops=-1
            currentBGM.play()
        }
    }

    func pauseBGM(){
        if currentBGM.playing {
            The currentBGM.pause()//pause() will disconnect from the sound file.And when it resumes, it starts from where it stops.
        } else{
            currentBGM.play()
        }
    }

}

In cases where it is guaranteed that it does not become nil, the instance variable can be Implicitly Unwrapped Optional (!) instead of Optional (?).Also, it is the programmer himself who makes a "guaranteed non-nil".

URLForResource() in NSBundle returns nil if the resource file retrieval fails.Therefore, you do not need to use the swift 2.0 exception handling.This time, under Programmer's Responsibility, we assumed that there must be a sound file, so if you want to consider the case where the sound file retrieval failed, use Optional Binding to branch conditions based on whether the variable is nil.

The prepareToPlay() method does not need to be called unless you are concerned about the time lag (delay) at the start of playback.


2022-09-30 20:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.