【问题标题】:Need help adding an audio file to a button in swift [closed]需要帮助快速将音频文件添加到按钮
【发布时间】:2014-12-22 04:17:27
【问题描述】:

任何人都可以帮助我让它工作我是一个菜鸟程序员,我找不到这样做的方法。

代码如下

import UIKit

class ViewController: UIViewController {

    @IBAction func pistolButton(sender: AnyObject) {

    }

    override func viewDidLoad() { // I want my audio file to play when button is tapped
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}

【问题讨论】:

  • 请编辑您的代码以使其具有某种意义,过多的空白和空函数不是一个好问题。有关提出好问题的指导,请参阅帮助中心。

标签: xcode swift xcode6


【解决方案1】:

斯威夫特 3

现在的语法如下:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()


    override func viewDidLoad() {
        super.viewDidLoad()
        // address of the music file
        let music = Bundle.main.path(forResource: "Music", ofType: "mp3")

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! ))
        }
        catch{
            print(error)
        }   
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func play(_ sender: AnyObject) {
        audioPlayer.play()   
    }
    @IBAction func stop(_ sender: AnyObject) {
        audioPlayer.stop()
    }
}

【讨论】:

    【解决方案2】:

    首先将您的声音拖到您的项目中,如果需要,选择复制到您的目标位置,然后选中“添加到目标”到您的应用。创建一个函数来播放您的声音,您还需要在代码开头添加 import AVFoundation,如下所示:

    import AVFoundation
    
    let beepSoundURL =  NSBundle.mainBundle().URLForResource("beep", withExtension: "aif")!
    var beepPlayer = AVAudioPlayer()
    func playMySound(){
       beepPlayer = AVAudioPlayer(contentsOfURL: beepSoundURL, error: nil)
       beepPlayer.prepareToPlay()
       beepPlayer.play()
    }
    
    @IBAction func pistolButton(sender: AnyObject) {
       playMySound()
    }
    

    【讨论】:

      【解决方案3】:

      Stack Overflow 上有很多不错的代码:

      Playing a sound with AVAudioPlayer

      下面是一些示例代码:

      import AVFoundation
      var audioPlayer: AVAudioPlayer?
      
      if let path = NSBundle.mainBundle().pathForResource("mysound", ofType: "aiff") {
          audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path), fileTypeHint: "aiff", error: nil)
      
          if let sound = audioPlayer {
              sound.prepareToPlay()
              sound.play()
          }
      }
      

      从这个位置:

      http://www.reddit.com/r/swift/comments/28izxl/how_do_you_play_a_sound_in_ios/

      【讨论】:

        猜你喜欢
        • 2022-10-26
        • 1970-01-01
        • 2010-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多