BackgroundMusic | Background Music , a macOS audio utility | Music Player library

 by   kyleneideck C++ Version: v0.4.0 License: GPL-2.0

kandi X-RAY | BackgroundMusic Summary

BackgroundMusic is a C++ library typically used in Audio, Music Player, macOS applications. BackgroundMusic has no bugs, it has no vulnerabilities, it has a Strong Copyleft License and it has medium support. You can download it from GitHub.
Background Music, a macOS audio utility: automatically pause your music, set individual apps' volumes and record system audio.
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        BackgroundMusic has a medium active ecosystem.
                        summary
                        It has 13309 star(s) with 618 fork(s). There are 147 watchers for this library.
                        summary
                        There were 1 major release(s) in the last 12 months.
                        summary
                        There are 418 open issues and 161 have been closed. On average issues are closed in 242 days. There are no pull requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of BackgroundMusic is v0.4.0
                        BackgroundMusic Support
                          Best in #Music Player
                            Average in #Music Player
                            BackgroundMusic Support
                              Best in #Music Player
                                Average in #Music Player

                                  kandi-Quality Quality

                                    summary
                                    BackgroundMusic has 0 bugs and 0 code smells.
                                    BackgroundMusic Quality
                                      Best in #Music Player
                                        Average in #Music Player
                                        BackgroundMusic Quality
                                          Best in #Music Player
                                            Average in #Music Player

                                              kandi-Security Security

                                                summary
                                                BackgroundMusic has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                BackgroundMusic code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                BackgroundMusic Security
                                                  Best in #Music Player
                                                    Average in #Music Player
                                                    BackgroundMusic Security
                                                      Best in #Music Player
                                                        Average in #Music Player

                                                          kandi-License License

                                                            summary
                                                            BackgroundMusic is licensed under the GPL-2.0 License. This license is Strong Copyleft.
                                                            summary
                                                            Strong Copyleft licenses enforce sharing, and you can use them when creating open source projects.
                                                            BackgroundMusic License
                                                              Best in #Music Player
                                                                Average in #Music Player
                                                                BackgroundMusic License
                                                                  Best in #Music Player
                                                                    Average in #Music Player

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        BackgroundMusic releases are available to install and integrate.
                                                                        summary
                                                                        Installation instructions, examples and code snippets are available.
                                                                        summary
                                                                        It has 6 lines of code, 0 functions and 2 files.
                                                                        summary
                                                                        It has low code complexity. Code complexity directly impacts maintainability of the code.
                                                                        BackgroundMusic Reuse
                                                                          Best in #Music Player
                                                                            Average in #Music Player
                                                                            BackgroundMusic Reuse
                                                                              Best in #Music Player
                                                                                Average in #Music Player
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
                                                                                  Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
                                                                                  Get all kandi verified functions for this library.
                                                                                  Get all kandi verified functions for this library.

                                                                                  BackgroundMusic Key Features

                                                                                  Background Music, a macOS audio utility: automatically pause your music, set individual apps' volumes and record system audio.

                                                                                  BackgroundMusic Examples and Code Snippets

                                                                                  No Code Snippets are available at this moment for BackgroundMusic.
                                                                                  Community Discussions

                                                                                  Trending Discussions on BackgroundMusic

                                                                                  How do I make all of a certain type of automatically generated sprites (that are on screen - or exist) move to a defined point on Phaser?
                                                                                  chevron right
                                                                                  How can I change the background music from one scene to another?
                                                                                  chevron right
                                                                                  Can i monitor a variable changed in another class in kotlin?
                                                                                  chevron right
                                                                                  I am getting an error with argument 1 must be pygame.Surface, not None. How do I fix this
                                                                                  chevron right
                                                                                  In LibGDX, how to stop music after Android app resumes?
                                                                                  chevron right
                                                                                  Mp3 audio is not playing in swift
                                                                                  chevron right
                                                                                  SwiftUI on appear AVAudioPlayer plays multiple times
                                                                                  chevron right
                                                                                  Background music destroyed when build index is 0
                                                                                  chevron right
                                                                                  How stop SKAction background music
                                                                                  chevron right
                                                                                  use winsound in a tkinter program from within a dictionary in python
                                                                                  chevron right

                                                                                  QUESTION

                                                                                  How do I make all of a certain type of automatically generated sprites (that are on screen - or exist) move to a defined point on Phaser?
                                                                                  Asked 2022-Mar-03 at 09:59

                                                                                  Very new to Phaser so I think I might be fundamentally misunderstanding something.

                                                                                  My game is supposed to be a clone of 'Jetpack Joyride' where the player jumps to avoid obstacles and collect coins etc.

                                                                                  I am currently trying to create a powerup which makes all of the coins on screen zoom towards the player (and therefore collect all of the coins).

                                                                                  I have used the this.physics.moveToObject function but it always gives me the error: 'Uncaught TypeError: Cannot read properties of undefined (reading 'velocity')'.

                                                                                  My thinking is that this function can't pull multiple objects at once - or it isn't able to 'locate' all instances of 'coins'(perhaps because of the way I have set up the random generation of them).

                                                                                  This could also be something to do with a basic syntax error on my end.

                                                                                  One issue I have noticed is, I need to actually destroy the sprites as they go off the screen - but not sure this is related to the above.

                                                                                  Anyway, any help is appreciated!

                                                                                  const gameState = {
                                                                                      score: 0,
                                                                                      endGame: 0, 
                                                                                      timer: 0,
                                                                                      text1: '',
                                                                                      text2: '',
                                                                                      music:'',
                                                                                      coinscore: 0,
                                                                                      coincollect:'',
                                                                                      speed: -400, 
                                                                                      coins: '',
                                                                                  };
                                                                                  
                                                                                  
                                                                                  class GameScene extends Phaser.Scene {
                                                                                      constructor() {
                                                                                        super({ key: 'GameScene' })
                                                                                      }
                                                                                  
                                                                                  
                                                                                  
                                                                                  create() {
                                                                                  
                                                                                  //Background 
                                                                                  this.createParalaxBackgrounds();
                                                                                  
                                                                                  //Add Timer 
                                                                                  gameState.timer = this.time.addEvent({
                                                                                      delay: 999999,
                                                                                      paused: false
                                                                                    });
                                                                                  
                                                                                  //Add Player
                                                                                  
                                                                                  var playerAnimation = this.anims.create({
                                                                                      key: 'run',
                                                                                      frames: [{
                                                                                          key: 'player',
                                                                                          frame: "sprite6"
                                                                                      }, {
                                                                                          key: 'player',
                                                                                          frame: "sprite16"
                                                                                      }],
                                                                                      frameRate: 5,
                                                                                      repeat: -1
                                                                                    });
                                                                                  
                                                                                  this.anims.create(playerAnimation);
                                                                                  
                                                                                  this.player = this.physics.add.sprite(320, 300, 'Player').setScale(3).setDepth(11).play('run');
                                                                                  this.player.setSize(15, 16, false);
                                                                                  
                                                                                  //Add Music
                                                                                  
                                                                                  //gameState.music = this.sound.add('BackgroundMusic', { loop: true});
                                                                                  gameState.coincollect = this.sound.add('coin_collect', {loop : false});
                                                                                  
                                                                                  
                                                                                  
                                                                                  
                                                                                  //Add World Physics
                                                                                  this.physics.world.setBounds(0, 0, 800, 600);
                                                                                  this.player.setCollideWorldBounds(true);
                                                                                  this.player.setImmovable(true);
                                                                                  
                                                                                  //Add Covid Physics
                                                                                  const covid = this.physics.add.group({immovable: true,
                                                                                      allowGravity: false});
                                                                                  covid.setDepth(11);
                                                                                  
                                                                                  gameState.coins = this.physics.add.group({immovable: true, allowGravity: false});
                                                                                  gameState.coins.setDepth(11);
                                                                                  
                                                                                  const magnets = this.physics.add.group({immovable: true, allowGravity: false})
                                                                                  magnets.setDepth(11);
                                                                                  
                                                                                  
                                                                                  
                                                                                  //Add Test Text
                                                                                  gameState.text1 = this.add.text(700, 10, `Score = ${gameState.score}`);
                                                                                  gameState.text1.setOrigin(0.5, 0.5).setDepth(11);
                                                                                  gameState.text2 = this.add.text(400, 50, `Coins Collected = ${gameState.coinscore}`, { fontSize: '15px', fill: '#000000' });
                                                                                  gameState.text2.setOrigin(0.5, 0.5).setDepth(11)
                                                                                  
                                                                                  //Random Score Used for Coin Spawn Generation
                                                                                  const CoinNumb = 500;
                                                                                  //Random Score Used for Enemy Spawn Generation
                                                                                  const RandomCovidGenNumb = 2000;
                                                                                  //Random Scored used for Magnet
                                                                                  const MagnetSpawnNumb = 4000;
                                                                                  // Enemy Spawn
                                                                                  function CovidGen () {
                                                                                      const yCoord = Math.random() * 600;
                                                                                      covid.create(800, yCoord, 'Covid').setDepth(11);
                                                                                      covid.setVelocityX(gameState.speed);
                                                                                  
                                                                                  }
                                                                                  
                                                                                  // Power Up Spawn 
                                                                                  
                                                                                  function MagnetGen() {
                                                                                      const yCoord = Math.random() * 600;
                                                                                      magnets.create(800, yCoord, 'coin_magnet').setDepth(11);
                                                                                      magnets.setVelocityX(gameState.speed);
                                                                                  
                                                                                  }
                                                                                  
                                                                                  // Adding Enemy Spawn Loop
                                                                                  const CovidGenLoop = this.time.addEvent({
                                                                                      delay: RandomCovidGenNumb,
                                                                                      callback: CovidGen,
                                                                                      callbackScope: this,
                                                                                      loop: true,
                                                                                   });
                                                                                  
                                                                                  // Adding Coin Spawn
                                                                                  function CoinGen () {
                                                                                      const yCoord = Math.random() * 600;
                                                                                      gameState.coins.create(800, yCoord, 'coin').setDepth(11).setScale(0.25);
                                                                                      gameState.coins.setVelocityX(gameState.speed);
                                                                                  
                                                                                  }
                                                                                  
                                                                                  // Adding Coin Spawn Loop
                                                                                  const CoinGenLoop = this.time.addEvent({
                                                                                      delay: CoinNumb,
                                                                                      callback: CoinGen,
                                                                                      callbackScope: this,
                                                                                      loop: true,
                                                                                   });
                                                                                  
                                                                                  const MagnetGenLoop = this.time.addEvent({
                                                                                      delay: MagnetSpawnNumb,
                                                                                      callback: MagnetGen,
                                                                                      callbackScope: this,
                                                                                      loop: true,
                                                                                   });
                                                                                  
                                                                                  
                                                                                  // Add Keyboard Input
                                                                                  const SpaceBar = this.input.keyboard.addKey('SPACE');
                                                                                  
                                                                                  
                                                                                  
                                                                                  //Setting Enemy Spawn Velocity
                                                                                  //covid.setVelocityX(-300);
                                                                                  
                                                                                  
                                                                                  
                                                                                  //Adding Collider between enemy and player + scene restart
                                                                                  this.physics.add.collider(this.player, covid, () => {
                                                                                      gameState.score += gameState.coinscore;
                                                                                      this.add.text(400, 300, `Game Over! \n Total Distance Travelled = ${gameState.score - gameState.coinscore} \n Total Coins Collected = ${gameState.coinscore} \n Total Score = ${gameState.score}`, { fontSize: '15px', fill: '#000000' }).setOrigin(0.5, 0.5).setDepth(11);
                                                                                      CovidGenLoop.destroy();
                                                                                      CoinGenLoop.destroy();
                                                                                      this.physics.pause();
                                                                                      gameState.timer.paused = true;
                                                                                      gameState.endGame += 1;
                                                                                      this.anims.pauseAll();
                                                                                      
                                                                                      this.input.on('pointerup', () => {
                                                                                          gameState.endGame -= 1;
                                                                                          this.scene.restart();
                                                                                          gameState.timer.remove();
                                                                                          gameState.coinscore = 0;
                                                                                          this.anims.resumeAll();
                                                                                  
                                                                                      });
                                                                                      
                                                                                  })
                                                                                  
                                                                                  //Adding Collider between player and coin
                                                                                  this.physics.add.collider(this.player, gameState.coins, (player, coin) => { 
                                                                                      coin.destroy();
                                                                                      gameState.coinscore += 1;
                                                                                      gameState.coincollect.play();
                                                                                  })
                                                                                  
                                                                                  //Adding Collider between player and magnet power up
                                                                                  
                                                                                  this.physics.add.collider(this.player, magnets, (player, magnet, coin) => { 
                                                                                      magnet.destroy();
                                                                                     
                                                                                      this.physics.moveToObject(gameState.coins, this.player, 200);
                                                                                  
                                                                                      
                                                                                      
                                                                                  
                                                                                  })
                                                                                  
                                                                                  
                                                                                  
                                                                                  
                                                                                  }

                                                                                  ANSWER

                                                                                  Answered 2022-Mar-03 at 09:59

                                                                                  Well the error is caused, because you are passing a group and not a gameobject to the function (details can befound in the documentation).
                                                                                  You could loop over all children/conis in the group, a call the function moveToObjecton each of them.

                                                                                  here a short demo (adapted from your code):

                                                                                  class GameScene extends Phaser.Scene {
                                                                                      constructor() {
                                                                                        super({ key: 'GameScene' });
                                                                                      }
                                                                                      
                                                                                      loadCoins(coins){
                                                                                      
                                                                                          for(let i = 0; i < 5; i++){
                                                                                              let yCoord = Math.random() * 200;
                                                                                              let coin = this.add.rectangle(400, yCoord, 15, 15, 0xFFFF00);
                                                                                              coin = this.physics.add.existing(coin);
                                                                                              coins.add(coin);
                                                                                          }  
                                                                                          coins.setVelocityX(-100); 
                                                                                      }
                                                                                      
                                                                                      create() {
                                                                                          this.running = true;
                                                                                          this.message = this.add.text(10, 10, 'Click to activate Magnet');
                                                                                          
                                                                                          this.player = this.add.rectangle(200, 100, 20, 20, 0xffffff);
                                                                                          this.physics.add.existing(this.player);
                                                                                  
                                                                                          //Add World Physics
                                                                                          this.physics.world.setBounds(0, 0, 400, 200);
                                                                                          this.player.body.setCollideWorldBounds(true);
                                                                                          this.player.body.setImmovable(true);
                                                                                  
                                                                                          let coins = this.physics.add.group({immovable: true, allowGravity: false});
                                                                                          
                                                                                          this.loadCoins(coins);
                                                                                   
                                                                                          this.input.on('pointerdown', _ => {
                                                                                              if(this.running){
                                                                                                  coins.children.each(coin =>  {
                                                                                                      // pull only coins infronz of the player
                                                                                                      if(coin.x >= this.player.x){
                                                                                                          this.physics.moveToObject(coin, this.player, 1500);
                                                                                                      }
                                                                                                  });
                                                                                                  this.message.text = 'Click to reset';
                                                                                              } else {
                                                                                                this.loadCoins(coins);
                                                                                                this.message.text = 'Click to activate Magnet';
                                                                                              }
                                                                                              this.running = !this.running;
                                                                                          });
                                                                                      
                                                                                      this.physics.add.collider(this.player, coins, 
                                                                                        (player, coin) => { 
                                                                                          coin.destroy();
                                                                                      });
                                                                                  
                                                                                    }
                                                                                  }
                                                                                  
                                                                                  const config = {
                                                                                      type: Phaser.AUTO,
                                                                                      width: 400,
                                                                                      height: 200,
                                                                                      scene: [ GameScene ],
                                                                                      physics: {
                                                                                         default: 'arcade',
                                                                                      }
                                                                                  };
                                                                                  
                                                                                  const game = new Phaser.Game(config);

                                                                                  Update:
                                                                                  I updated the code, so that "coins", that are behind the player won't be fulled. This can be tweeked to:

                                                                                  • only pull coins in a specific distance
                                                                                  • only pull coins that are visible
                                                                                  • and so on

                                                                                  Source https://stackoverflow.com/questions/71315668

                                                                                  QUESTION

                                                                                  How can I change the background music from one scene to another?
                                                                                  Asked 2022-Jan-07 at 10:16

                                                                                  There are only two scenes in my game. The first is the menu and the second is the game. In the second scene I added background music and I made sure that when reloading the scene the music did not interrupt, but this means that when returning to the menu the music continues overlapping that of the menu.

                                                                                  Can you give me any solutions please? Thank you!

                                                                                  This is the code to make the music continue with the scene reloads:

                                                                                  using UnityEngine;
                                                                                  using UnityEngine.SceneManagement;
                                                                                  
                                                                                  public class BackgroundMusic : MonoBehaviour
                                                                                  {
                                                                                      private static BackgroundMusic backgroundMusic;
                                                                                      
                                                                                      void Awake()
                                                                                      {
                                                                                      
                                                                                         if (backgroundMusic == null)
                                                                                          {
                                                                                              backgroundMusic = this;
                                                                                              DontDestroyOnLoad(backgroundMusic);
                                                                                              Debug.Log(SceneManager.GetActiveScene().name);
                                                                                          }
                                                                                          else
                                                                                          {
                                                                                              Destroy(gameObject);
                                                                                          }
                                                                                      }
                                                                                  
                                                                                  }
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Dec-23 at 00:43

                                                                                  Put the same game object with the BackgroundMusic script on both of the scenes. Since you implemented the singleton pattern, this will ensure that only 1 music player will ever play at one time.

                                                                                  Now, subscribe to SceneManager.sceneLoaded so that you can change the music based on the scene, like so:

                                                                                  using UnityEngine.SceneManagement;
                                                                                  
                                                                                  public class BackgroundMusic : MonoBehaviour
                                                                                  {
                                                                                      private static BackgroundMusic backgroundMusic;
                                                                                  
                                                                                      void Awake() 
                                                                                      { 
                                                                                          // Keep singleton pattern implementation here 
                                                                                          SceneManager.onSceneLoaded += SwitchMusic;
                                                                                      }
                                                                                  
                                                                                      void SwitchMusic()
                                                                                      {
                                                                                          // Logic to change music tracks here.
                                                                                          // You could have an array of AudioClip and index 
                                                                                          // that array by the scene's build index, for instance.
                                                                                  
                                                                                          // You can also just check if scenes actually changed, and if not,
                                                                                          // you can make the music just continue without changing.
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  Let me know in the comments if you have any questions.

                                                                                  Source https://stackoverflow.com/questions/70455006

                                                                                  QUESTION

                                                                                  Can i monitor a variable changed in another class in kotlin?
                                                                                  Asked 2022-Jan-02 at 20:33

                                                                                  Im in a fragment1 and i want go to fragment2 if an event occurred in a class called from the fragment1. I have tried a callback of fuction: function in Class call a function in fragment1 to go in fragment but i collect this error:

                                                                                  Process: com.example.ilmiogioco, PID: 7992java.lang.IllegalStateException: Method addObserver must be called on the main thread
                                                                                  at androidx.lifecycle.LifecycleRegistry.enforceMainThreadIfNeeded(LifecycleRegistry.java:317)
                                                                                  at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:172)
                                                                                  at androidx.savedstate.SavedStateRegistryController.performRestore(SavedStateRegistryController.java:61)
                                                                                  at androidx.navigation.NavBackStackEntry.(NavBackStackEntry.java:88)
                                                                                  at androidx.navigation.NavBackStackEntry.(NavBackStackEntry.java:73)
                                                                                  at androidx.navigation.NavController.navigate(NavController.java:1138)
                                                                                  at androidx.navigation.NavController.navigate(NavController.java:944)
                                                                                  at androidx.navigation.NavController.navigate(NavController.java:877)
                                                                                  at androidx.navigation.NavController.navigate(NavController.java:863)
                                                                                  at androidx.navigation.NavController.navigate(NavController.java:851)
                                                                                  at com.example.ilmiogioco.FullscreenFragmentSolo.follow(FullscreenFragmentSolo.kt:77)
                                                                                  at com.example.ilmiogioco.Solo.SpaceView.update(SpaceView.kt:276)
                                                                                  at com.example.ilmiogioco.Solo.SpaceView.run(SpaceView.kt:120)
                                                                                  at java.lang.Thread.run(Thread.java:919)
                                                                                  

                                                                                  EDIT: I have fullscreenfragmentsolo (fragment1) that want in gameoverfragment (fragment2) if the class spaceview called in fullscreenfragmentsolo collect a lost game. The function follow() is called by spaceview for return in fullscreenfragmentsolo (maybe this is the thread error).

                                                                                   class FullscreenFragmentSolo : Fragment() {
                                                                                  
                                                                                  private var spaceView: SpaceView? = null
                                                                                  private lateinit var backgroundMusic: MediaPlayer
                                                                                  private lateinit var window: Window
                                                                                  private var binding: FragmentFullscreenSoloBinding? = null
                                                                                  object size{
                                                                                      var x = 0
                                                                                      var y = 0
                                                                                  }
                                                                                  
                                                                                  
                                                                                  override fun onCreateView(
                                                                                      inflater: LayoutInflater, container: ViewGroup?,
                                                                                      savedInstanceState: Bundle?
                                                                                  ): View? {
                                                                                      (activity as AppCompatActivity?)!!.supportActionBar!!.hide()
                                                                                      getActivity()?.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                                                                                  
                                                                                      val soundEffects = SoundEffects(requireContext())
                                                                                  
                                                                                      soundEffects.playSound(SoundEffects.backgroundMusic)
                                                                                  
                                                                                      val outMetrics = DisplayMetrics()
                                                                                  
                                                                                      getActivity()?.getWindow()?.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                                                                                      window = activity?.getWindow()!!
                                                                                      window.attributes.width
                                                                                      window.attributes.height
                                                                                  
                                                                                      if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                                                                                          val display = activity?.display
                                                                                          display?.getRealMetrics(outMetrics)
                                                                                      } else {
                                                                                          @Suppress("DEPRECATION")
                                                                                          val display = activity?.windowManager?.defaultDisplay
                                                                                          @Suppress("DEPRECATION")
                                                                                          display?.getMetrics(outMetrics)
                                                                                      }
                                                                                  
                                                                                      size.y = outMetrics.heightPixels
                                                                                      size.x = outMetrics.widthPixels
                                                                                  
                                                                                      backgroundMusic = MediaPlayer.create(requireContext(), R.raw.background_music)
                                                                                      backgroundMusic.isLooping = true
                                                                                      backgroundMusic.start()
                                                                                      val fragmentBinding = FragmentFullscreenSoloBinding.inflate(inflater, container, false)
                                                                                      binding = fragmentBinding
                                                                                      fragmentBinding.root
                                                                                      spaceView = SpaceView(requireContext(), size, this)
                                                                                  
                                                                                      return spaceView
                                                                                  }
                                                                                  fun follow(){
                                                                                  
                                                                                      findNavController().navigate(R.id.action_fullscreenFragmentSolo_to_gameoverFragment)
                                                                                  }
                                                                                  
                                                                                  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
                                                                                      super.onViewCreated(view, savedInstanceState)
                                                                                      binding?.soloFragment = this
                                                                                  }
                                                                                  
                                                                                  override fun onResume() {
                                                                                      super.onResume()
                                                                                  
                                                                                      spaceView?.resume()
                                                                                  }
                                                                                  fun stopFunction() {
                                                                                      spaceView?.stop()
                                                                                  }
                                                                                  
                                                                                  override fun onPause() {
                                                                                      super.onPause()
                                                                                  
                                                                                      backgroundMusic.release()
                                                                                      spaceView?.pause()
                                                                                  
                                                                                  }
                                                                                  override fun onDestroyView() {
                                                                                      super.onDestroyView()
                                                                                      binding = null
                                                                                  }
                                                                                  

                                                                                  GameoverFragment:

                                                                                  open class GameoverFragment : Fragment() {
                                                                                  private var binding: GameoverFragmentBinding? = null
                                                                                  
                                                                                  
                                                                                  override fun onCreateView(
                                                                                      inflater: LayoutInflater, container: ViewGroup?,
                                                                                      savedInstanceState: Bundle?
                                                                                  ): View? {
                                                                                  
                                                                                      // Inflate the layout for this fragment
                                                                                      val fragmentBinding = GameoverFragmentBinding.inflate(inflater, container, false)
                                                                                      binding = fragmentBinding
                                                                                      return fragmentBinding.root
                                                                                      return view
                                                                                  }
                                                                                  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
                                                                                      super.onViewCreated(view, savedInstanceState)
                                                                                      binding?.gameoverFragment = this
                                                                                  }
                                                                                  fun Menu(){
                                                                                      findNavController().navigate(R.id.action_gameoverFragment_to_startFragment)
                                                                                  }
                                                                                  
                                                                                  > override fun onDestroyView() {
                                                                                  >     super.onDestroyView()
                                                                                  >     binding = null }
                                                                                  

                                                                                  Can you help me?

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-02 at 20:33

                                                                                  This exception is due to your code calling (through navigation) the LifecycleRegistry.addObserver from a thread other than the Main thread. You have to ensure that you call the navigation from the main thread.

                                                                                  Change to this in the follow() function

                                                                                  import android.os.Handler
                                                                                  import android.os.Looper
                                                                                  
                                                                                  // ...
                                                                                  
                                                                                  fun follow() {
                                                                                      Handler(Looper.getMainLooper()).post {
                                                                                          findNavController().navigate(R.id.action_fullscreenFragmentSolo_to_gameoverFragment)
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/70558979

                                                                                  QUESTION

                                                                                  I am getting an error with argument 1 must be pygame.Surface, not None. How do I fix this
                                                                                  Asked 2021-Dec-10 at 12:05

                                                                                  I am following a code tutorial on YouTube and for some reason my code wont execute as it is producing this error code. Please assist, thank you.

                                                                                  Traceback (most recent call last): File "H:\Year 12 ict\game project\space game booster WORKING.py", line 194, in main() File "H:\Year 12 ict\game project\space game booster WORKING.py", line 192, in main redraw_window() File "H:\Year 12 ict\game project\space game booster WORKING.py", line 144, in redraw_window enemy.draw(WINDOW) File "H:\Year 12 ict\game project\space game booster WORKING.py", line 81, in draw window.blit(self.player_img, (self.x, self.y)) TypeError: argument 1 must be pygame.Surface, not None

                                                                                  The code is:

                                                                                  import pygame
                                                                                  import os
                                                                                  import random
                                                                                  import time
                                                                                  pygame.font.init()
                                                                                  
                                                                                  pygame.init()
                                                                                  
                                                                                  pygame.mixer.music.load(os.path.join("assets", 
                                                                                  "BackgroundMusic.mp3"))
                                                                                  

                                                                                  #Game window

                                                                                  WIDTH, HEIGHT = 500,500
                                                                                  WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
                                                                                  pygame.display.set_caption("Shootergame")
                                                                                  
                                                                                  #Player player
                                                                                  PLAYER_SPACE_SHIP = pygame.image.load(os.path.join("assets", "pixel_ship_player.png"))
                                                                                  
                                                                                  #Enemy players
                                                                                  EMS_1 = pygame.image.load(os.path.join("assets", "space_enemy_1R.png"))
                                                                                  EMS_2 = pygame.image.load(os.path.join("assets", "space_enemy_2R.png"))
                                                                                  EMS_3 = pygame.image.load(os.path.join("assets", "space_enemy_3R.png"))
                                                                                  EMS_4 = pygame.image.load(os.path.join("assets", "space_enemy_4R.png"))
                                                                                  
                                                                                  #Asteroids
                                                                                  ASTEROID_1 = pygame.image.load(os.path.join("assets", "asteroid_1R.png"))
                                                                                  ASTEROID_2 = pygame.image.load(os.path.join("assets", "asteroid_2R.png"))
                                                                                  ASTEROID_3 = pygame.image.load(os.path.join("assets", "asteroid_3R.png"))
                                                                                  
                                                                                  #Boss 
                                                                                  BOSS = pygame.image.load(os.path.join("assets", "bossR.png"))
                                                                                  
                                                                                  #Lasers
                                                                                  RED_LZ = pygame.image.load(os.path.join("assets", "red_laserR.png"))
                                                                                  GREEN_LZ = pygame.image.load(os.path.join("assets", "green_laserR.png"))
                                                                                  BLUE_LZ = pygame.image.load(os.path.join("assets", "blue_laserR.png"))
                                                                                  PURPLE_LZ = pygame.image.load(os.path.join("assets", "purple_laserR.png"))
                                                                                  
                                                                                  BACKGROUND = pygame.transform.scale(pygame.image.load(os.path.join("assets", "bg.png")), (WIDTH,HEIGHT))
                                                                                  boost = False
                                                                                  boost_speed = 8
                                                                                  
                                                                                  def score_write():
                                                                                          d = shelve.open('score.txt','w')
                                                                                          d['score'] = score
                                                                                          d.close()
                                                                                  
                                                                                  def score_read():
                                                                                          d = shelve.open('score.txt')
                                                                                          score = d['score']
                                                                                          d.close()
                                                                                  
                                                                                  def score_multiply():
                                                                                          if time <= 50:
                                                                                              score = score*10
                                                                                          if time <= 100 and time > 50:
                                                                                              score = score*5
                                                                                          if time <= 150 and time > 100:
                                                                                              score = score*3
                                                                                          if time <= 200 and time > 150:
                                                                                              score = score*2
                                                                                          if time > 200:
                                                                                              score = score
                                                                                  
                                                                                  
                                                                                  
                                                                                  class ship:
                                                                                      def __init__(self, x,y, health=100):
                                                                                          self.x = 220
                                                                                          self.y = 450
                                                                                          self.health = health
                                                                                          self.player_img = None
                                                                                          self.laser_img = None
                                                                                          self.lasers = []
                                                                                          self.cool_down = 0
                                                                                  
                                                                                      def draw(self, window):
                                                                                          window.blit(self.player_img, (self.x, self.y))
                                                                                  
                                                                                      def get_width(self):
                                                                                          return self.player_img.get_width()
                                                                                  
                                                                                      def get_height(self):
                                                                                          return self.player_img.get_height()
                                                                                  
                                                                                  class Player(ship):
                                                                                      def __init__(self, x, y, health=100):
                                                                                          super().__init__(x,y, health)
                                                                                          self.player_img = PLAYER_SPACE_SHIP
                                                                                          self.laser_img = RED_LZ
                                                                                          self.mask =     pygame.mask.from_surface(self.player_img)
                                                                                          self.max_health = health
                                                                                  
                                                                                  class Em(ship):
                                                                                      COLOUR_MAP = {
                                                                                                   "red": (EMS_1, RED_LZ),
                                                                                                   "green": (EMS_2, GREEN_LZ),
                                                                                                   "purple": (EMS_3, PURPLE_LZ),
                                                                                                   "blue": (EMS_4, BLUE_LZ)
                                                                                                   }
                                                                                      def __init__(self, x, y, colour, health=100):
                                                                                          super().__init__(x, y, health)
                                                                                          self.ship_img, self.laser_img =     self.COLOUR_MAP[colour]
                                                                                          self.mask = pygame.mask.from_surface(self.ship_img)
                                                                                  
                                                                                      def move(self,vel):
                                                                                          self.y += vel
                                                                                      
                                                                                  
                                                                                  def main():
                                                                                  
                                                                                  run = True
                                                                                  FPS = 60
                                                                                  level = 1
                                                                                  hp = 2
                                                                                  boostspeed = 4
                                                                                  player_vel = 3
                                                                                  boost = player_vel + 5
                                                                                  main_font = pygame.font.SysFont("comicsans", 40)
                                                                                  clock = pygame.time.Clock()
                                                                                  pygame.mixer.music.play(loops=-1)
                                                                                  
                                                                                  enemies = []
                                                                                  wave_length = 5
                                                                                  enemy_vel = 1
                                                                                  
                                                                                  boost = 10
                                                                                  
                                                                                  player = Player(300,650)
                                                                                  
                                                                                  def redraw_window():
                                                                                      WINDOW.blit(BACKGROUND, (0,0))
                                                                                  
                                                                                      hp_label = main_font.render(f"HP: {hp}", 1, (255,255,255))
                                                                                      level_label = main_font.render(f"Level: {level} ", 1, (255,255,255))
                                                                                  
                                                                                      WINDOW.blit(hp_label, (10, 10))
                                                                                      WINDOW.blit(level_label, (WIDTH - level_label.get_width() - 10,10))
                                                                                  
                                                                                      for enemy in enemies:
                                                                                              enemy.draw(WINDOW)
                                                                                  
                                                                                      player.draw(WINDOW)
                                                                                  
                                                                                      
                                                                                      pygame.display.update()
                                                                                      
                                                                                      
                                                                                  while run:
                                                                                      clock.tick(FPS)
                                                                                  
                                                                                      if len(enemies) == 0:
                                                                                              level += 1
                                                                                              wave_length += 5
                                                                                              for i in range(wave_length):
                                                                                                      enemy = Em(random.randrange(50, WIDTH-10), random.randrange(-1500*level/5, -100), random.choice(["red","green","purple","blue"]))
                                                                                                      enemies.append(enemy)
                                                                                      boost = False
                                                                                      for event in pygame.event.get():
                                                                                          if event.type == pygame.QUIT:
                                                                                              run = False
                                                                                      keys = pygame.key.get_pressed()
                                                                                     
                                                                                      if keys[pygame.K_LEFT] and player.x - player_vel > 0:
                                                                                          player.x -= player_vel
                                                                                      if keys[pygame.K_RIGHT] and player.x + player_vel + player.get_width() < WIDTH:
                                                                                          player.x += player_vel
                                                                                      if keys[pygame.K_UP] and player.y - player_vel > 0:
                                                                                          player.y -= player_vel
                                                                                      if keys[pygame.K_DOWN] and player.y + player_vel + player.get_height() < HEIGHT:
                                                                                          player.y += player_vel
                                                                                  
                                                                                      if keys[pygame.K_LSHIFT]:
                                                                                          boost = True
                                                                                          start = time.time()
                                                                                          if boost == True:
                                                                                              player_vel = boost_speed
                                                                                              
                                                                                              
                                                                                  
                                                                                  
                                                                                      elif event.type == pygame.KEYUP:
                                                                                          if event.key == pygame.K_LSHIFT:
                                                                                              player_vel = 3
                                                                                  
                                                                                      for enemy in enemies:
                                                                                              enemy.move(enemy_vel)
                                                                                      
                                                                                      redraw_window()        
                                                                                  
                                                                                  main()
                                                                                  score_write()
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Dec-10 at 12:05

                                                                                  Try changing self.player_img = None to self.player_img = pygame.Surface((0, 0)) in the ship class. Also, when you load an image, use .convert or .convert_alpha() at the end, for example img = pygame.image.load("image.png").convert_alpha(). It should improve the performance.

                                                                                  You can also put this in draw() before blitting:

                                                                                  if not self.player_img:
                                                                                      return
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/70288557

                                                                                  QUESTION

                                                                                  In LibGDX, how to stop music after Android app resumes?
                                                                                  Asked 2021-Nov-19 at 06:21

                                                                                  I'm developing a simple game in Kotlin using LibGDX that plays music in the background. On Android, when the user is playing the game and presses the HOME button, then resumes the game once more, my pause screen appears - and the music resumes. What I want is for the music to always be off whenever my pause screen is being displayed.

                                                                                  When I start up a new game, whenever I press my in-game "pause" button, the music stops as intended - then starts again once I click my in-game "resume" button. That's working just fine. It's only when pressing the HOME button that I have issues.

                                                                                  I found this JavaDoc comment in the LibGDX doc: https://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/badlogic/gdx/audio/Music.html

                                                                                  Music instances are automatically paused and resumed when an Application is paused or resumed. See ApplicationListener.

                                                                                  That is not the behaviour I want but I can't figure out how to stop it. I've tried to stop the music when the app resumes but none of that seems to have any effect - the music always plays.

                                                                                  I'm using an Assets class, following the recommendations here: libgdx: best way to load all assets in the game

                                                                                  Here's my Assets class:

                                                                                  class Assets {
                                                                                      . . .
                                                                                      private val manager = AssetManager()
                                                                                  
                                                                                      lateinit var backgroundMusic: Music
                                                                                      . . .
                                                                                  
                                                                                      fun load() {
                                                                                          manager.load(BACKGROUND_MUSIC_FILENAME, Music::class.java)
                                                                                      }
                                                                                  
                                                                                      fun finishLoading() {
                                                                                          // Wait for all loading to finish
                                                                                          manager.finishLoading()
                                                                                          . . .
                                                                                          backgroundMusic = manager.get(BACKGROUND_MUSIC_FILENAME)
                                                                                      }
                                                                                  
                                                                                      fun startBackgroundMusic() {
                                                                                          if (Preferences.musicEnabled) {
                                                                                              backgroundMusic.isLooping = true
                                                                                              backgroundMusic.volume = 1f
                                                                                              backgroundMusic.play()
                                                                                          }
                                                                                      }
                                                                                  
                                                                                      fun stopBackgroundMusic() {
                                                                                          backgroundMusic.stop()
                                                                                      }
                                                                                  . . .
                                                                                  }
                                                                                  

                                                                                  My main entry point looks like this:

                                                                                  class GameEntrypoint : Game(), ScreenSwitcher {
                                                                                  
                                                                                      private val assets = Assets()
                                                                                  
                                                                                      override fun create() {
                                                                                          // Start loading assets
                                                                                          assets.load()
                                                                                  
                                                                                          // Wait until all assets have loaded
                                                                                          assets.finishLoading()
                                                                                          . . .
                                                                                          mainMenuScreen = MainMenuScreen(assets, this, this.penguinGame)
                                                                                          setScreen(mainMenuScreen)
                                                                                      }
                                                                                  

                                                                                  Here's my GameScreen where I switch to the PauseScreen when the app is paused:

                                                                                  class GameScreen(private val assets: Assets, private val screenSwitcher: ScreenSwitcher,  . . .) : Screen,
                                                                                      InputProcessor {
                                                                                  
                                                                                      init {
                                                                                          . . .
                                                                                          val btnPause = ImageButton(TextureRegionDrawable(assets.imagesTextureAtlas.findRegion(Assets.BUTTON_PAUSE_REGION)))
                                                                                          Gui.addClickListener(btnPause) {
                                                                                              // Pause button clicked - pause the game then show pause screen
                                                                                              pauseTheGame()
                                                                                          }
                                                                                          . . .
                                                                                      }
                                                                                  
                                                                                      private fun pauseTheGame() {
                                                                                          assets.stopBackgroundMusic()
                                                                                          penguinGame.pauseGame()
                                                                                          screenSwitcher.setScreen(pauseScreen)
                                                                                      }
                                                                                      . . .
                                                                                  }
                                                                                  

                                                                                  I've tried calling assets.stopBackgroundMusic() in these places:

                                                                                  • In resume() of GameEntrypoint
                                                                                  • In resume() of PauseScreen
                                                                                  • In show() of PauseScreen
                                                                                  • Whenever the game is paused from GameScreen

                                                                                  I'm out of ideas. Any help or ideas greatly appreciated!

                                                                                  ANSWER

                                                                                  Answered 2021-Nov-19 at 06:21

                                                                                  I've found a couple of ways to resolve this issue.

                                                                                  It's caused by the following code in com.badlogic.gdx.backends.android.AndroidApplication:

                                                                                      @Override
                                                                                      protected void onResume () {
                                                                                      . . .
                                                                                          this.isWaitingForAudio = true;
                                                                                          if (this.wasFocusChanged == 1 || this.wasFocusChanged == -1) {
                                                                                              this.audio.resume(); // <--- here !!
                                                                                              this.isWaitingForAudio = false;
                                                                                          }
                                                                                          super.onResume();
                                                                                      }
                                                                                  

                                                                                  As you can see, the audio is always resumed. Why? I dunno.

                                                                                  So to solve it, you can do one of the following:

                                                                                  1. Add the following code to AndroidLauncher:
                                                                                      override fun onResume() {
                                                                                          super.onResume()
                                                                                          // Work-around to prevent LibGDX from *always* restarting background music after resume
                                                                                          this.audio.pause()
                                                                                      }
                                                                                  

                                                                                  This will turn the music off, straight after it's turned on again inside super.resume().

                                                                                  1. Add the following code to the end of the create function in your class that extends Game:
                                                                                      override fun create() {
                                                                                          . . .
                                                                                          // Don't play any music from when the app was last resumed
                                                                                          assets.stopBackgroundMusic()
                                                                                      }
                                                                                  
                                                                                  

                                                                                  I'd still like to know why LibGDX behaves this way.

                                                                                  Source https://stackoverflow.com/questions/69986023

                                                                                  QUESTION

                                                                                  Mp3 audio is not playing in swift
                                                                                  Asked 2021-Oct-19 at 09:59

                                                                                  this is my swift class

                                                                                  import Foundation
                                                                                  import AVFoundation
                                                                                  
                                                                                  class MusicPlayer{
                                                                                      static let shared  = MusicPlayer()
                                                                                      var audioPlayer: AVAudioPlayer?
                                                                                      
                                                                                      func startBackgroundMusic(backgroundMusicFileName: String) {
                                                                                          if let bundle = Bundle.main.path(forResource: backgroundMusicFileName, ofType: "mp3") {
                                                                                              let backgroundMusic = NSURL(fileURLWithPath: bundle)
                                                                                              do {
                                                                                                  audioPlayer = try AVAudioPlayer(contentsOf:backgroundMusic as URL)
                                                                                                  guard let audioPlayer = audioPlayer else { return }
                                                                                                  audioPlayer.numberOfLoops = -1
                                                                                                  audioPlayer.volume = 1.0
                                                                                                  audioPlayer.prepareToPlay()
                                                                                                  audioPlayer.play()
                                                                                              } catch {
                                                                                                  print(error)
                                                                                              }
                                                                                          }
                                                                                      }
                                                                                      
                                                                                      func stopBackgroundMusic() {
                                                                                          guard let audioPlayer = audioPlayer else { return }
                                                                                          audioPlayer.stop()
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  And, here is my code for the Controller class

                                                                                  func downloadUsingAlamofire() {
                                                                                          let audioUrl =  URL(string:"https://www.learningcontainer.com/wp-content/uploads/2020/02/Kalimba.mp3")
                                                                                          let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
                                                                                          Alamofire.download(
                                                                                              audioUrl!,
                                                                                              method: .get,
                                                                                              parameters: nil,
                                                                                              encoding: URLEncoding.default,
                                                                                              headers: nil,
                                                                                              to: destination).downloadProgress(closure: { (progress) in
                                                                                              }).response(completionHandler: { (DefaultDownloadResponse) in
                                                                                                  let imageURL = fetchPathinDirectory(filepath:audioUrl!.lastPathComponent)
                                                                                                  MusicPlayer.shared.startBackgroundMusic(backgroundMusicFileName: imageURL.path)
                                                                                                  
                                                                                              })
                                                                                      }
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Oct-19 at 09:37

                                                                                  As explain in comment ;

                                                                                  let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
                                                                                  

                                                                                  That means the file is downloaded in documents directory of your app. But when you read the file :

                                                                                   if let bundle = Bundle.main.path(forResource: backgroundMusicFileName, ofType: "mp3") {
                                                                                      let backgroundMusic = NSURL(fileURLWithPath: bundle)
                                                                                  

                                                                                  You read for file in application bundle which is where your application and its ressources (storyboard, xib, …) are installed. You must read the file from documents directory. Something like :

                                                                                  var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                                                                                  let downloadedFileUrl = documentsURL.appendingPathComponent(backgroundMusicFileName)
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/69626299

                                                                                  QUESTION

                                                                                  SwiftUI on appear AVAudioPlayer plays multiple times
                                                                                  Asked 2021-Jul-06 at 01:21

                                                                                  Im trying to add a AVAudioPlayer for background music on my app, I am initiating the player at the main screen, trying to start playing when the app opens but get unexpected behavior...
                                                                                  It plays and instantly keeps sort of creating new players and playing those players so there is tens of the same sound playing at the same time

                                                                                  Initiating and playing function for the music

                                                                                  if let path = Bundle.main.path(forResource: sound, ofType: type) {
                                                                                      do {
                                                                                          backgroundPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                                                                                          backgroundPlayer?.play()
                                                                                      } catch {
                                                                                          print("BACKGROUND MUSIC ERROR")
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  On appear call for the function
                                                                                  .onAppear {
                                                                                      audioController.backgroundMusic(sound: "bg", type: "wav")
                                                                                  }
                                                                                  

                                                                                  Edit: Example code ...

                                                                                  import SwiftUI
                                                                                  import AVKit
                                                                                  
                                                                                  struct ContentView: View {
                                                                                      @ObservedObject var audioController = AudioController()
                                                                                  
                                                                                      var body: some View {
                                                                                           Text("Hello, world!")
                                                                                               .onAppear {
                                                                                                   audioController.playBackgroundMusic(sound: "bg", type: "wav")
                                                                                               }
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  class AudioController: ObservableObject {
                                                                                       var player: AVAudioPlayer?    
                                                                                  
                                                                                       func playBackgroundMusic(sound: String, type: String) {
                                                                                          if let path = Bundle.main.path(forResource: sound, ofType: type) {
                                                                                              do {
                                                                                                  player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                                                                                                  player?.play()
                                                                                              } catch {
                                                                                                  print("BACKGROUND MUSIC ERROR")
                                                                                              }
                                                                                          }
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Jul-06 at 01:21

                                                                                  you could try something like this:

                                                                                  func playBackgroundMusic(sound: String, type: String) {
                                                                                      if !(player?.isPlaying ?? false) {
                                                                                          if let path = Bundle.main.path(forResource: sound, ofType: type) {
                                                                                              do {
                                                                                                  player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                                                                                                  player?.play()
                                                                                              } catch {
                                                                                                  print("BACKGROUND MUSIC ERROR")
                                                                                              }
                                                                                          }
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/68263249

                                                                                  QUESTION

                                                                                  Background music destroyed when build index is 0
                                                                                  Asked 2021-Jun-13 at 16:53

                                                                                  I've got this background sound playing throughout the game. The problem is that I want it to stop when the scene index is 0.

                                                                                  using System.Collections;
                                                                                  using System.Collections.Generic;
                                                                                  using UnityEngine;
                                                                                  using UnityEngine.SceneManagement;
                                                                                  
                                                                                  public class BackgroundMusic : MonoBehaviour
                                                                                  {
                                                                                  
                                                                                  void Start()
                                                                                  {
                                                                                      GameObject[] objs = GameObject.FindGameObjectsWithTag("music");
                                                                                      if (objs.Length > 1)
                                                                                      {
                                                                                          Destroy(this.gameObject);
                                                                                      }
                                                                                      if (SceneManager.GetActiveScene().buildIndex != 0)
                                                                                      {
                                                                                          DontDestroyOnLoad(this.gameObject);
                                                                                      }
                                                                                  
                                                                                  }
                                                                                  

                                                                                  I've been using this script but still doesn't work Any suggestions?

                                                                                  ANSWER

                                                                                  Answered 2021-Jun-13 at 16:53

                                                                                  If you use DontDestroyOnLoad it is "forever" you don't have to do it for each scene again.

                                                                                  And then note that after that the Start is not called for every scene load again only the first time!

                                                                                  Rather use SceneManager.sceneLoaded like e.g.

                                                                                  public class BackgroundMusic : MonoBehaviour
                                                                                  {
                                                                                  
                                                                                      private static BackgroundMusic _instace;
                                                                                  
                                                                                      private void Awake()
                                                                                      {
                                                                                          if (_instance && _instance != this)
                                                                                          {
                                                                                              Destroy(this.gameObject);
                                                                                              return;
                                                                                          }
                                                                                          
                                                                                          DontDestroyOnLoaddd(this.gameObject);
                                                                                          _instance = this;
                                                                                  
                                                                                          SceneManager.sceneLoaded += OnSceneLoaded;
                                                                                      }
                                                                                  
                                                                                      private void OnDestroy ()
                                                                                      {
                                                                                          SceneManager.sceneLoaded -= OnSceneLoaded;
                                                                                      }
                                                                                  
                                                                                      private void OnSceneLoaded (Scene scene, LoadSceneMode mode)
                                                                                      {
                                                                                          if(scene.buildIndex == 0)
                                                                                          {
                                                                                              // TODO disable música
                                                                                              // NOTE: I wouldn't Destroy this though but rather only stop the music
                                                                                          }
                                                                                          else
                                                                                          {
                                                                                              // TODO enable the music
                                                                                          }
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/67959474

                                                                                  QUESTION

                                                                                  How stop SKAction background music
                                                                                  Asked 2021-Mar-26 at 10:10

                                                                                  I'm trying to make a game and in the main menu, there is a label to start music, and another to stop music.

                                                                                  let backgroundMusic = SKAction.playSoundFileNamed("background.mp3", waitForCompletion: false)
                                                                                  
                                                                                   override func touchesEnded(_ touches: Set, with event: UIEvent?) {
                                                                                          for touch in touches {
                                                                                              let location = touch.location(in: self)
                                                                                              let touchedNode = atPoint(location)
                                                                                              if touchedNode.name == self.BEGIN_MUSIC {
                                                                                                  // start music
                                                                                                  self.run(backgroundMusic)
                                                                                              }
                                                                                              if touchedNode.name == self.STOP_MUSIC {
                                                                                                  // stop music
                                                                                                  SKAction.stop()
                                                                                              }
                                                                                          }
                                                                                      }
                                                                                  

                                                                                  the music starts fine and works on all scenes which is what i wanted. But when I press the stop music, the music keeps playing. How do I stop the music.

                                                                                  I've tried SKAction.pause(), i've tried using withKey: "music" and then self.removeAction(forKey: "music").

                                                                                  I also tried making backgroundMusic: SKAudioNode and this worked but once i stopped the music i couldn't turn it back on, also it doesn't work on any other scene just the main menu.

                                                                                  How do I stop the sound?

                                                                                  ANSWER

                                                                                  Answered 2021-Mar-26 at 10:10

                                                                                  I've had the same issue a while ago: This is how I got it working. This is specific for background music.

                                                                                     var backgroundMusic: AVAudioPlayer!
                                                                                  
                                                                                  
                                                                                     func playMusic() {
                                                                                        if let musicURL = Bundle.main.url(forResource: "musicSource", withExtension: "wav") {
                                                                                            if let audioPlayer = try? AVAudioPlayer(contentsOf: musicURL) {
                                                                                                backgroundMusic = audioPlayer
                                                                                                backgroundMusic.numberOfLoops = -1
                                                                                                backgroundMusic.play()
                                                                                                backgroundMusic.volume = 0.2
                                                                                              
                                                                                            }    
                                                                                        }
                                                                                     }
                                                                                  
                                                                                  
                                                                                     override func touchesEnded(_ touches: Set, with event: UIEvent?) {
                                                                                       super.touchesBegan(touches, with: event)
                                                                                  
                                                                                        if let touch = touches.first {
                                                                                            let pos = touch.location(in: self)
                                                                                            let node = self.atPoint(pos)
                                                                                  
                                                                                         let musicOff = UserDefaults.standard.bool(forKey: "musicOff")
                                                                                  
                                                                                         if node == musicButton && musicOff == false {
                                                                                  
                                                                                                 backgroundMusic.stop()
                                                                                                 UserDefaults.standard.set(true, forKey: "musicOff")
                                                                                  
                                                                                         }
                                                                                  
                                                                                         if node == musicButton && musicOff == true {
                                                                                  
                                                                                                  backgroundMusic.play()
                                                                                                  backgroundMusic.volume = 0.3
                                                                                                  UserDefaults.standard.set(false, forKey: "musicOff")
                                                                                  
                                                                                         }
                                                                                       }
                                                                                     }
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/66810155

                                                                                  QUESTION

                                                                                  use winsound in a tkinter program from within a dictionary in python
                                                                                  Asked 2021-Jan-19 at 16:26

                                                                                  I have edited the code a bit would this new code work and if not what should i do to get it to work

                                                                                  import winsound
                                                                                  
                                                                                  import tkinter as tk
                                                                                  from functools import partial # a quick way to make a callback function
                                                                                  import choose_your_own_adventure_game_pt2 as AG
                                                                                  import time
                                                                                  winsound.PlaySound('Adrenaline - Intense Suspense Music (No Copyright).wav', winsound.SND_ASYNC)
                                                                                  print('welcome to the')
                                                                                  AG.title()
                                                                                  time.sleep(1)
                                                                                  print('please read each line carefuly once the gui launches')
                                                                                  time.sleep(13)
                                                                                  
                                                                                  
                                                                                  class Situation(tk.Frame):
                                                                                      
                                                                                      def __init__(self, master=None, story='',song=[], buttons=[], **kwargs):
                                                                                          tk.Frame.__init__(self, master, **kwargs)
                                                                                  
                                                                                          story_lbl = tk.Label(self, text=story, justify=tk.LEFT, anchor=tk.NW, font=("Play", 10))
                                                                                          story_lbl.pack()
                                                                                          
                                                                                          for btn_text, new_situation in buttons:
                                                                                              btn = tk.Button(self, text=btn_text, command=partial(self.quit_, new_situation),padx=10, pady=10)
                                                                                              btn.pack()
                                                                                          def song_startup(self, new_sound):
                                                                                              
                                                                                              winsound.PlaySound(btn_song_filename, winsound.SND_ASYNC|winsound.SND_FILENAME)
                                                                                          
                                                                                              for btn_song_filename, new_sound in song:
                                                                                                  btn_song = tk.Button(self, text=btn_song_filename, command=partial(self.song_startup, new_sound))
                                                                                                  btn_song.pack()
                                                                                  
                                                                                      def quit_(self, new_situation):
                                                                                          self.destroy()
                                                                                          load(new_situation)
                                                                                  
                                                                                  def load(situation=None):
                                                                                      frame = Situation(root, **SITUATIONS.get(situation))
                                                                                      frame.pack()
                                                                                  
                                                                                  SITUATIONS = {
                                                                                      
                                                                                      None:{
                                                                                          'song':
                                                                                          'intro to the game.wav',
                                                                                          'story':
                                                                                          
                                                                                  """
                                                                                  
                                                                                  
                                                                                  
                                                                                  hello player you have been chosen to embark on your first adventure,
                                                                                  
                                                                                  this as a button based game so all your decisions are based on a press of a button,
                                                                                  
                                                                                  you will play as a character named Sarah who has a wolf goddess inside her, the goddess' name is Winter,
                                                                                  
                                                                                  you as Sarah will have the powers given to you by Winter to get through this game but if you use too much
                                                                                  of that power at any given time your game will end,
                                                                                  
                                                                                  pretty soon you will be asked a series of questions your job is to choose the answer that best suits your style of playing the game
                                                                                  
                                                                                  but be warned you may end up loosing in the end, so without furthur addo lets start this thing
                                                                                  
                                                                                  welcome to 
                                                                                                                        
                                                                                  MOON LANDING EXPIDITION                                             
                                                                                                                               
                                                                                  male scientist:Hello Sarah can you hear me?
                                                                                  
                                                                                  
                                                                                  """,
                                                                                  
                                                                                          'buttons':[
                                                                                              ('YES', 'situation_2'),
                                                                                              
                                                                                              ('NO','situation_2_1')
                                                                                              ]
                                                                                          },
                                                                                      'situation_2':{
                                                                                          'story':
                                                                                  """
                                                                                  
                                                                                  
                                                                                  male scientist:good... do you know where you are?
                                                                                          
                                                                                          
                                                                                          
                                                                                  """,
                                                                                  'song':[
                                                                                  
                                                                                  ('backgroundmusic.wav')
                                                                                  ],
                                                                                          'buttons' :[
                                                                                              ('yes', 'situation_3'),
                                                                                              
                                                                                              ('no', 'situation_3_1')
                                                                                              ]                  
                                                                                          },
                                                                                      'situation_2_1':{
                                                                                          'story':
                                                                                  """
                                                                                  
                                                                                  male scientist: hmm if you can't hear me
                                                                                  then you wouldn't have responded
                                                                                  
                                                                                  
                                                                                  """,
                                                                                          'buttons':[
                                                                                              ('-_-',None)
                                                                                              
                                                                                              ]
                                                                                          
                                                                                          },
                                                                                      'situation_3':{
                                                                                          'story':
                                                                                  """
                                                                                  
                                                                                  male scientist:alright so do you know why you are here?
                                                                                  """,
                                                                                           'buttons':[
                                                                                               ('yes','situation_4'),
                                                                                  
                                                                                               ('no','situation_4_1')
                                                                                               
                                                                                               ]
                                                                                          
                                                                                          },
                                                                                      'situation_3_1':{
                                                                                          'story':
                                                                                  """
                                                                                  
                                                                                  male scientist: you are in a top secret military space center
                                                                                  """,
                                                                                         'buttons':[
                                                                                             ('alright','situation_3')
                                                                                             
                                                                                             ]    
                                                                                          },
                                                                                      'situation_4':{
                                                                                          'story':
                                                                                  """
                                                                                  male scientist:well then you seem to have the rare ability to read people's minds
                                                                                  
                                                                                  (a second scientist enters the room and starts talking to the first on the other side of the glass)
                                                                                  
                                                                                  female scientist:Dr. Smith there has been sightings of foreign aircrafts approaching our location
                                                                                  
                                                                                  Dr. Smith: alright Susan we need to transport Sarah to the space explorer
                                                                                  
                                                                                  Susan:Yes Sir
                                                                                  
                                                                                  (Susan looks in your direction)
                                                                                  
                                                                                  Susan:Sarah will you please head to the door behind you and follow the yellow lines on the floor
                                                                                  """,
                                                                                       'buttons':[
                                                                                           ('what is going on?','situation_5'),
                                                                                           ('do not press', 'never_gonna_give_you_up'),
                                                                                           ('am i in danger?','situation_5_1'),
                                                                                           ('ok','situation_5_2')
                                                                                           
                                                                                           ],    
                                                                                          },
                                                                                              'situation_4_1':{
                                                                                          'story':
                                                                                  """
                                                                                  male scientist:you were chosen out of five million individuals to take part in a space exploration mission to the planet nexu...
                                                                                  
                                                                                  (a second scientist enters the room and starts talking to the first on the other side of the glass)
                                                                                  
                                                                                  female scientist:Dr. Smith there has been sightings of foreign aircrafts approaching our location
                                                                                  
                                                                                  Dr. Smith: alright Susan we need to transport Sarah to the space explorer
                                                                                  
                                                                                  Susan:Yes Sir
                                                                                  
                                                                                  (Susan looks in your direction)
                                                                                  
                                                                                  Susan:Sarah will you please head to the door behind you and follow the yellow lines on the floor
                                                                                  """,
                                                                                       'buttons':[
                                                                                           ('what is going on?','situation_5'),
                                                                                           ('am i in danger?','situation_5_1'),
                                                                                           ('ok','situation_5_2')
                                                                                           
                                                                                           ],    
                                                                                          },    
                                                                                              'never_gonna_give_you_up':{
                                                                                                  'story':
                                                                                  """
                                                                                  were no strangers to love...
                                                                                  
                                                                                  
                                                                                  you know the rules and so do i...
                                                                                  
                                                                                  iiiiiiiii just wanna tell you how im feeling 
                                                                                  
                                                                                  gotta make you UNDERSTAND!!!
                                                                                  
                                                                                  never gonna give you up never gonna let you down 
                                                                                  
                                                                                  *rick astly.exe has sotpped working you will die now*
                                                                                  """,
                                                                                      'buttons':[
                                                                                          ('death', None)
                                                                                          
                                                                                          ],
                                                                                    
                                                                                                  },
                                                                                      }
                                                                                  def beginning():
                                                                                      start_button.destroy()
                                                                                      load() # load the first story
                                                                                      winsound.PlaySound(None, winsound.SND_ASYNC)
                                                                                  #WINDOW
                                                                                  root = tk.Tk()
                                                                                  root.geometry('500x500-500-300')
                                                                                  root.title('Moon landing expedition')
                                                                                  root.attributes('-fullscreen', True)
                                                                                  #START
                                                                                  start_button = tk.Button(root, text="START", command=beginning)
                                                                                  start_button.place(relx=.5, rely=.5, anchor='c')
                                                                                  
                                                                                  
                                                                                  
                                                                                  
                                                                                  #THE LOOP
                                                                                  root.mainloop()
                                                                                  

                                                                                  thank you to everyone who has contributed to help me get my code to work I really appreciate all the help I'm receiving and I would like you guys to know that I try every suggestion that comes my way. i hope i can get my code to finaly work as it is really important for me to get it to work

                                                                                  ANSWER

                                                                                  Answered 2021-Jan-15 at 16:05

                                                                                  Add a song item in each situation like:

                                                                                  'situation_2': {
                                                                                      'story': ...
                                                                                      'song': 'situation_2.wav',
                                                                                      'buttons': [...]
                                                                                  },
                                                                                  

                                                                                  Then add song argument in Situation.__init__() and play the song using PlaySound():

                                                                                  class Situation(tk.Frame):
                                                                                      def __init__(self, master=None, story='', buttons=[], song=None, **kwargs):
                                                                                          tk.Frame.__init__(self, master, **kwargs)
                                                                                  
                                                                                          story_lbl = tk.Label(self, text=story, justify=tk.LEFT, anchor=tk.NW, font=("Play", 10))
                                                                                          story_lbl.pack()
                                                                                          
                                                                                          for btn_text, new_situation in buttons:
                                                                                              btn = tk.Button(self, text=btn_text, command=partial(self.quit_, new_situation), padx=10, pady=10)
                                                                                              btn.pack()
                                                                                  
                                                                                          if song:
                                                                                              winsound.PlaySound(song, winsound.SND_ASYNC)
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/65738845

                                                                                  Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                  Vulnerabilities

                                                                                  No vulnerabilities reported

                                                                                  Install BackgroundMusic

                                                                                  You can download the current version of Background Music using the following options. We also have snapshot builds.

                                                                                  Support

                                                                                  If Background Music crashes and your audio stops working, open System Preferences > Sound and change your system's default output device to something other than the Background Music device. If it already is, then change the default device and then change it back again. Make sure you allow "microphone access" when you first run Background Music. If you denied it, go to System Preferences > Security & Privacy > Privacy > Microphone, find Background Music in the list and check the box next to it. Background Music doesn't actually listen to your microphone. It needs the permission because it gets your system audio from its virtual input device, which macOS counts as a microphone. (We're working on it in #177.). If the volume slider for an app isn't working, try looking in More Apps for entries like Some App (Helper). For some meeting or video chat apps, you may need to do this to change the current meeting volume.
                                                                                  Find more information at:
                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit

                                                                                  Share this Page

                                                                                  share link

                                                                                  Explore Related Topics

                                                                                  Consider Popular Music Player Libraries

                                                                                  Try Top Libraries by kyleneideck

                                                                                  webui-vulns

                                                                                  by kyleneideckHTML

                                                                                  Compare Music Player Libraries with Highest Support

                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit