无法在 xcode 6 swift 中播放音频
Posted
技术标签:
【中文标题】无法在 xcode 6 swift 中播放音频【英文标题】:Unable to play audio in xcode 6 swift 【发布时间】:2014-11-30 11:05:02 【问题描述】:import UIKit
import AVFoundation
class PlaySoundViewController: UIViewController
var audioplayer: AVAudioPlayer!
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3")
var fileUrl = NSURL.fileURLWithPath(filePath)
audioplayer = AVAudioPlayer(contentsOfURL: fileUrl, error: nil)
else
println("path file is empty")
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
@IBAction func PlaySoundSlow(sender: UIButton)
audioplayer.play()
【问题讨论】:
【参考方案1】:我一般做一个声音类,然后用一个函数来调用声音播放,像这样:
声音类:
class Sound
//properties
var fileName = ""
var fileExtension = ""
//custom init
init(fileName: String, fileExtension: String)
self.fileName = fileName
self.fileExtension = fileExtension
播放声音功能:
// 需要 AVAudioPlayer?实例
// 需要 AVFoundation 导入
// 需要 AVAudioPlayerDelegate
var audioPlayer: AVAudioPlayer()
func playSound(声音:声音)
让 dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatchQueue, [weak self] in let mainBundle = NSBundle.mainBundle() /* Find the location of our file to feed to the audio player */ let filePath = mainBundle.pathForResource(sound.fileName, ofType:sound.fileExtension) if let path = filePath let fileData = NSData(contentsOfFile: path) var error:NSError? /* Start the audio player */ self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error) /* Did we get an instance of AVAudioPlayer? */ if let player = self!.audioPlayer /* Set the delegate and start playing */ player.delegate = self if player.prepareToPlay() && player.play() /* Successfully started playing */ else /* Failed to play */ else /* Failed to instantiate AVAudioPlayer */ )
希望这对您有所帮助。
【讨论】:
以上是关于无法在 xcode 6 swift 中播放音频的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Xcode11 中的 Swift 中随机播放数组中的音频文件?