iOS AVAudioPlayer - 如何将文件路径设置为pathForResource

标签 ios avaudioplayer

我想在单击按钮时播放小 mp3 文件。但不知道如何在 setPathForResources 中设置 mp3 文件

这是我的代码

import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {

    var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("/sounds/superman", ofType: "mp3")!)
    var audioPlayer = AVAudioPlayer()


    @IBOutlet weak var PlaySlow: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

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

    @IBAction func PlaySlowAction(sender: UIButton) {
      audioPlayer.play()
    }

我仅通过拖放即可将 sounds 文件夹添加到项目中。但是当我单击按钮时,我收到此错误。

audioPlayer.play()线程1:EXC_BAD_ACCESS(Code=1,address=0x1c)

最佳答案

您不需要 sounds/在你的道路上。只是文件名。例如

var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("superman", ofType: "mp3")!)

还有fileURLWithPath接受一个 URL,而不是一个字符串。您需要转换您的NSBundle.mainBundle().pathForResource("superman", ofType: "mp3")首先使用 NSURL(string:) 到字符串.

这是完整的设置:

let path = NSBundle.mainBundle().pathForResource("superman", ofType:"mp3")
let fileURL = NSURL(fileURLWithPath: path)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.delegate = self
player.play()

关于iOS AVAudioPlayer - 如何将文件路径设置为pathForResource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27604345/

相关文章:

ios - 将对 IBOutlet 和 IBAction 的引用放在 viewDidLoad 内还是之前?

ios - 为什么导航栏中未显示 uiactivity 指示器

objective-c - 在 iOS 上使用 AVAudioPlayer 需要哪些框架和导入?

ios - 从 CMSampleBuffer 播放音频

ios - 当用户点击 "Play Again"时,如何在 Swift 中重置数组

ios - 如果用户删除应用程序,则从服务器中删除用户

ios - Facebook iOS SDK 'one-time' 授权

ios - 设置 iOS MPMusicPlayerController 相对于 AVAudioPlayer 的音量

ios - 提高/增加文本转语音 (AVSpeechUtterance) 的音量以使其声音更大

iphone - 在设备锁定时播放 iPod 库中的音频