在Xcode 7 / Swift 2中播放音频不起作用

时间:2015-07-30 04:46:20

标签: ios xcode audio swift2 xcode7

我目前正在使用Swift 2的Xcode 7 beta 4,尝试播放音频。我的代码中没有任何错误,但是当我按下播放按钮时,音频不会播放。我无法弄清楚出了什么问题。

    call    ___main
    flds    LC1
    fstps   24(%esp)
L7:
    flds    24(%esp)
/APP
 # 484 "F:/Prog/mingw-w64/i686-4.9.2-win32-dwarf-rt_v4-rev2/mingw32/i686-w64-mingw32/include/math.h" 1
    fxam; fstsw %ax;
 # 0 "" 2
/NO_APP
    andw    $17664, %ax
    cmpw    $1024, %ax
    sete    %al
    movzbl  %al, %eax
    movl    %eax, 12(%esp)
    fstpl   4(%esp)
    movl    $LC2, (%esp)
    call    _printf
    flds    24(%esp)
    fstps   (%esp)
    call    _PrintBytes
    movl    $LC3, (%esp)
    call    _puts
    flds    24(%esp)
/APP
 # 484 "F:/Prog/mingw-w64/i686-4.9.2-win32-dwarf-rt_v4-rev2/mingw32/i686-w64-mingw32/include/math.h" 1
    fxam; fstsw %ax;
 # 0 "" 2
/NO_APP
    andw    $17664, %ax
    cmpw    $1024, %ax
    jne L6
    fmuls   LC4
    fstps   24(%esp)
    jmp L7
L6:
    fstp    %st(0)
    movl    $0, %eax
    leave
    .cfi_restore 5
    .cfi_def_cfa 4, 4
    ret
    .cfi_endproc
LFE41:
    .section .rdata,"dr"
    .align 4
LC1:
    .long   8388608
    .align 4
LC4:
    .long   1056964608

更新 正确的代码:

import UIKit
import AVFoundation

class VesuviusViewController: UIViewController {

    @IBOutlet weak var PausePlay: UIButton!

    func playVes() {
        do {

        _ = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ves", ofType: "m4a")!))

        } catch {
            print("Error")
        }
    }

    @IBAction func playButtonPressed(sender: AnyObject) {
        playVes()
    }

    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.

    }
}

2 个答案:

答案 0 :(得分:12)

试试这个:

var audioPlayer: AVAudioPlayer! // Global variable

玩法:

func playVes() {
        do {
            self.audioPlayer =  try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ves", ofType: "m4a")!))
            self.audioPlayer.play()

        } catch {
            print("Error")
        }
    }

希望这有帮助!

答案 1 :(得分:0)

不确定为什么会发生这种情况,但有多种方法可以在项目中实现声音。试试这个:

class Hello : UIViewController {

  var Audio1 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("mySound", ofType: "wav")!)
  var AudioPlayer = AVAudioPlayer()

override func viewDidLoad() {

  AudioPlayer = AVAudioPlayer(contentsOfURL: Audio1, error: nil)
}

func playsound() {

  AudioPlayer.play()

}