简体   繁体   中英

How to play sound using media volume instead of ring volume in ios?

I am trying to play a sound but my current code bases the volume off of the ringtone volume. How to I change this to media volume?

var player: AVAudioPlayer?

...

func playSound(name: String) {
        let url = Bundle.main.url(forResource: name, withExtension: "mp3")!

        do {
            player = try AVAudioPlayer(contentsOf: url)
            guard let player = player else { return }

            player.prepareToPlay()
            player.play()
        } catch let error {
            print(error.localizedDescription)
        }
    }

...

playSound(name: "baby")

只有在你将一些网址放入播放器之前才设置它。

 try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)

To play sound using media volume you should do like this:

func play(){

        let path = Bundle.main.path(forResource: "Plop", ofType: "mp3")!
        let url = URL(fileURLWithPath: path)

        do {
            let sound = try AVAudioPlayer(contentsOf: url)
            bombSoundEffect = sound
            sound.play()
        } catch {
            // couldn't load file :(
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM