如何在swift3中播放mp3文件?

时间:2023-01-24 11:51:20

I have started to learn ios development and am stuck in one place. My code to play mp3 file is

我已经开始学习ios开发并被困在一个地方。我播放mp3文件的代码是

var bombSoundEffect: AVAudioPlayer!
let path = Bundle.main.path(forResource: "faded", ofType:"mp3")!
let url = NSURL(fileURLWithPath: path)

 do {
        let sound = try AVAudioPlayer(contentsOf: (url as NSURL) as URL)
        bombSoundEffect.play()

    } catch {
        print("couldn't load file :(")
    }
    if bombSoundEffect != nil {
        bombSoundEffect.stop()
        bombSoundEffect = nil
        }

However, when I click on the button, my file doesn't play. The song is playing perfectly normally.

但是,当我点击按钮时,我的文件无法播放。这首歌正常播放。

2 个解决方案

#1


4  

Try with the follow code:

尝试使用以下代码:

var bombSoundEffect: AVAudioPlayer?

func playAudio() {
    let url = Bundle.main.url(forResource: "faded", withExtension: "mp3")!

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

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

#2


3  

There's lots wrong with your code, but it's a sunny day, so try something like this…

您的代码有很多问题,但这是一个阳光灿烂的日子,所以尝试这样的事情......

func playSound() {
    guard let url = Bundle.main.url(forResource: "faded", withExtension: "mp3") else { return }

    let bombSoundEffect = try? AVAudioPlayer(contentsOf: url)
    bombSoundEffect?.play()
}

#1


4  

Try with the follow code:

尝试使用以下代码:

var bombSoundEffect: AVAudioPlayer?

func playAudio() {
    let url = Bundle.main.url(forResource: "faded", withExtension: "mp3")!

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

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

#2


3  

There's lots wrong with your code, but it's a sunny day, so try something like this…

您的代码有很多问题,但这是一个阳光灿烂的日子,所以尝试这样的事情......

func playSound() {
    guard let url = Bundle.main.url(forResource: "faded", withExtension: "mp3") else { return }

    let bombSoundEffect = try? AVAudioPlayer(contentsOf: url)
    bombSoundEffect?.play()
}