AVAudioPlayer Swift 3无法播放声音 [英] AVAudioPlayer Swift 3 not playing sound

查看:111
本文介绍了AVAudioPlayer Swift 3无法播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将AVFoundation.framework添加到了我的项目中.在我的项目导航器中,添加了文件"Horn.mp3",声音为1秒.

I added the AVFoundation.framework to my project. In my project navigator I added the file "Horn.mp3", this is a sound of 1 second.

按下按钮(带有喇叭声)时,声音应该播放,标签也应该更改其文本.

When a button is pressed (with a image of a horn) the sound should play, also should a label change it's text.

标签正在更改其文本,但声音没有播放.

The label is changing it's text, but the sound isn't playing.

这是我的代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBAction func hornButtonPressed(_ sender: Any) {
        playSound()
        hornLabel.text = "Toet!!!"
    }

    @IBOutlet weak var hornLabel: UILabel!

    func playSound(){
        var player: AVAudioPlayer?
        let sound = Bundle.main.url(forResource: "Horn", withExtension: "mp3")
        do {
            player = try AVAudioPlayer(contentsOf: sound!)
            guard let player = player else { return }
            player.prepareToPlay()
            player.play()
        } catch let error {
            print(error.localizedDescription)
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

推荐答案

您需要将 AVPlayer 的声明移到类级别.在方法中声明 AVPlayer 时无法播放声音.

You need to move the AVPlayer's declaration to class-level. AVPlayer can't play sounds when you declare them in methods.

class ViewController: UIViewController {
    var player: AVAudioPlayer? // <-- notice here

    @IBAction func hornButtonPressed(_ sender: Any) {
        playSound()
        hornLabel.text = "Toet!!!"
    }

    @IBOutlet weak var hornLabel: UILabel!

    func playSound(){
        let sound = Bundle.main.url(forResource: "Horn", withExtension: "mp3")
        do {
            player = try AVAudioPlayer(contentsOf: sound!)
            guard let player = player else { return }
            player.prepareToPlay()
            player.play()
        } catch let error {
            print(error.localizedDescription)
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

这篇关于AVAudioPlayer Swift 3无法播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆