音频文件无法播放iOS 8 swift

时间:2014-08-02 10:00:34

标签: audio swift ios8

这是我使用的代码:

var aSound = NSURL(fileURLWithPath:  NSBundle.mainBundle().pathForResource("abc", ofType: "mp3"))

var audioPlayer = AVAudioPlayer()

        println(aSound)

        audioPlayer = AVAudioPlayer(contentsOfURL: aSound, error: nil)

        audioPlayer.prepareToPlay()

        audioPlayer.play()

我试图打印文件的路径,这就是我在控制台中看到的内容。

file:///Users/<username>/Library/Developer/CoreSimulator/Devices/<some GUID>/data/Containers/Bundle/Application/<some different GUID>/HelloWorld.app/abc.mp3

我已经通过执行&#34;将文件添加到项目&#34;将mp3添加到我的项目中从菜单中。 当我运行模拟器时它会自动添加到上面的位置吗?

3 个答案:

答案 0 :(得分:0)

var audio: AVAudioPlayer = AVAudioPlayer()

@IBAction func playaudio(sender: AnyObject) //method for playing audio {

var audioPath = NSString(string: NSBundle.mainBundle().pathForResource("bus", ofType: "mp3")!)

    var error: NSError? = nil

    //instantiate the player
    audio = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath as String), error: &error)
    audio.prepareToPlay()
    audio.play()
}

override func viewDidLoad() 
{

    super.viewDidLoad()

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

并且不要忘记导入AVFoundation Framework。

答案 1 :(得分:0)

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("fileName", ofType: "extension"))
        println(alertSound)
            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()
    }

}

答案 2 :(得分:0)

使用此功能在Swift中发出声音(您可以在想要发声的地方使用此功能。)

首先添加SpriteKit Framework。

import SpriteKit
    func playEffectSound(filename: String){
         runAction(SKAction.playSoundFileNamed("\(filename)", waitForCompletion: false))
    }
// use this function to play sound

    playEffectSound("Sound File Name With Extension")
// Example :- playEffectSound("BS_SpiderWeb_CollectEgg_SFX.mp3")