Swift-为什么我无法播放声音?

问题描述 投票:0回答:2

为什么这不起作用?我搜索了向 Xcode 添加声音的方法,发现了很多不同的方法。我以为我已经弄清楚系统是如何工作的,但出了问题,但我看不到问题所在。

import AVFoundation
var audioPlayer = AVAudioPlayer!

func playSound(sound: String){
        let url = Bundle.main.url(forResource: sound, withExtension: "mp3")
        audioPlayer = try! AVAudioPlayer(contentsOf: url!)
        audioPlayer.play()
    }

 if userGotItRight{
            //true answer
            playSound(sound: "CorrectAnswer")
            
        }else{
            //false answer
            playSound(sound: "WrongAnswer")
            
        }
swift xcode audio avaudioplayer playsound
2个回答
0
投票

如果你想播放本地的声音,你可以使用这个:

import AVFoundation

var player: AVAudioPlayer?

func playSound(_ soundName: String) {
    guard let url = NSBundle.mainBundle().URLForResource(soundName, withExtension: "mp3") else { 
        print("URL is wrong") return
    }
    do {
        player = try AVAudioPlayer(contentsOfURL: url)
        guard let player = player else { return }

        player.prepareToPlay()
        player.play()

    } catch {
       print(error.description)
    }
}

然后你可以像这样调用该函数:

if userGotItRight {
    playSound("CorrectAnswer") 
} else {
    playSound("WrongAnswer")
}

0
投票

Swift 5、Xcode 14

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player: AVAudioPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func keyPressed(_ sender: UIButton) {
        playSound()
    }
    
    func playSound() {
            let url = Bundle.main.url(forResource: "C", withExtension: "wav")
            player = try! AVAudioPlayer(contentsOf: url!)
            player.play()
                    
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.