我想在单独的类(而不是viewController类)中的swift应用程序中播放mp3文件,并识别声音的结尾。我的代码在AppDelegate.swift中发送了EXC_BAD_ACCESS。
这里是我的代码:
UIViewController.swift
class ViewController: UIViewController, AVAudioPlayerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let soundM = soundManager()
soundM.loadFile("glass_ping", soundType: "mp3")
soundM.playNow()
soundManager.swift
import Foundation
import AVFoundation
var audioPlayer = AVAudioPlayer();
class soundManager: NSObject, AVAudioPlayerDelegate {
override init()
{
super.init();
print("hallo")
}
func playNow(){
audioPlayer.play()
}
func loadFile(_ soundName: String, soundType: String){
let sound = Bundle.main.path(forResource: soundName, ofType: soundType)
do{
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.rate = 2.0
//audioPlayer.numberOfLoops = 2
}catch{
print(error)
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print("finish")
}
任何想法?
谢谢
我发现了一个非常奇怪的解决方案,我不确定它为什么起作用:
UIViewController.swift
import UIKit
import AVFoundation
class ViewController: UIViewController {
private var player: AudioPlayerComposition!
@IBOutlet weak var power: Visualizer!
override func viewDidLoad() {
super.viewDidLoad()
// Get URL to resouce, create audioPlayer
let audioPlayer = AVAudioPlayer();
player = AudioPlayer(player: audioPlayer)
//player.play()
AudioPlayer.swift
import Foundation
import AVFoundation
class AudioPlayer: NSObject, AVAudioPlayerDelegate {
private var player: AVAudioPlayer
init(player: AVAudioPlayer, view: Visualizer) {
self.player = player
super.init()
self.loadFile("test", soundType: "mp3")
}
func loadFile(_ soundName: String, soundType: String){
let sound = Bundle.main.path(forResource: soundName, ofType: soundType)
do {
self.player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
self.player.prepareToPlay()
self.player.play()
}catch{
print(error)
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print ("Finish")
}
这确实有效。但是,何况没有线索?