[英]swift- playing a series of audio files
嗨,我想一個接一個地播放5個音頻文件。
我有一些代碼將發揮作用。
有誰知道如何一個接一個地播放一組音頻文件?
謝謝
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var audioPlayer: AVAudioPlayer?
/* The delegate message that will let us know that the player
has finished playing an audio file */
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!,
successfully flag: Bool) {
println("Finished playing the song")
}
override func viewDidLoad() {
super.viewDidLoad()
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 */
var x = 1
let filePath = mainBundle.pathForResource("\(x)", ofType:"mp3")
// }
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 */
}
}
})
}
}
您可以使用ColiseuPlayer ,它是用Swift編寫的音頻播放器框架。 它仍處於測試階段,但您可以使用它或檢查代碼。
演示:
import UIKit
import ColiseuPlayer
class ViewController: UIViewController {
let player = ColiseuPlayer()
override func viewDidLoad() {
super.viewDidLoad()
var list = [AudioFile]()
if let urlFile = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("1.m4a", ofType: nil)!) {
list.append(AudioFile(url: urlFile))
}
if let urlFile = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("2.m4a", ofType: nil)!) {
list.append(AudioFile(url: urlFile))
}
if list.count > 0 {
// Play first song (it will continue playing with the current playlist)
player.playSong(0, songsList: list)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.