gpt4 book ai didi

xcode - 无法以XCode 6 Swift播放音频

转载 作者:行者123 更新时间:2023-12-03 02:06:57 28 4
gpt4 key购买 nike

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()
}

最佳答案

我通常制作一个声音类,然后使用一个函数来调用声音,如下所示:

声音等级:

class Sound {
//properties
var fileName = ""
var fileExtension = ""

//custom init
init(fileName: String, fileExtension: String) {
self.fileName = fileName
self.fileExtension = fileExtension
}
}

playSound功能:

// requires AVAudioPlayer? instance

// requires AVFoundation import

// requires AVAudioPlayerDelegate

var audioPlayer: AVAudioPlayer()

func playSound (sound: Sound) {

let 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 - 无法以XCode 6 Swift播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27212540/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com