为什么声音不起作用?

时间:2014-11-18 15:50:41

标签: ios swift

    //
//  ViewController.swift
//  MinecraftSoundApp
//
//  Created by Abdel Rahman Osman on 11/18/14.
//  Copyright (c) 2014 Abdel Rahman Osman. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController {


  var audioPlayer: AVAudioPlayer?

    @IBAction func Creeper(sender: AnyObject) {
        var player = AVPlayer(URL: NSURL(fileURLWithPath: "/Users/abdelrahman/Downloads/Minecraft Creeper Sound sSSSsss BOOM_.mp3"))
        player.play()

    }
    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模拟器运行它时,我听不到声音。

1 个答案:

答案 0 :(得分:0)

我在主套装中添加了一个mp3文件,并按如下方式更新了代码。我希望它也适用于您使用过的网址

//
//  ViewController.swift
//  MinecraftSoundApp
//
//  Created by Abdel Rahman Osman on 11/18/14.
//  Copyright (c) 2014 Abdel Rahman Osman. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController {


  var audioPlayer = AVAudioPlayer()

    @IBAction func Creeper(sender: AnyObject) {
        var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("01 - Aggobai Daggobai", ofType: "mp3")!)
        println(alertSound)

        // Removed deprecated use of AVAudioSessionDelegate protocol
        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
        AVAudioSession.sharedInstance().setActive(true, error: nil)

        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
        audioPlayer.prepareToPlay()
        audioPlayer.play()

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


}