ios - AVAudioPlayer Swift 3 不播放声音

标签 ios swift audio avaudioplayer

<分区>

我将 AVFoundation.framework 添加到我的项目中。在我的项目导航器中,我添加了文件“Horn.mp3”,这是 1 秒的声音。

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

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

这是我的代码:

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 无法播放声音。

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.
    }


}

关于ios - AVAudioPlayer Swift 3 不播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42748014/

相关文章:

vb6 - 如何在VB6中录制麦克风的声音?

objective-c - 覆盖不使用 UITableView 滚动 - iOS

ios - API 网关 : Empty request body?

ios - 理解 SpriteKit 中的重力和向量

swift - 在 Swift 中从 ISO-8601 字符串中提取偏移值

ios - 本地通知声音没有播放?

ios - 80 年代的 4 月 1 日日期在 iOS 10.0 中无法解析

ios - 快速访问应用程序委托(delegate)变量延迟 View 加载

ios - 如何使 TableView Controller 上的 View 覆盖导航栏?

android - 如何在android中播放旋律?