The other day, I wrote a program for audio playback, but it doesn't play.Thank you for pointing it out.
import UIKit
import AVFoundation
classViewController:UIViewController {
varplayer —AVAudioPlayer?
let sound_data = NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource("sample", ofType:"mp3")!)
override func viewDidLoad(){
super.viewDidLoad()
// Do any additional setup after loading the view, typically from anib.
do{
letplayer=try AVAudioPlayer(contentsOfURL:sound_data)
player.play()
}
catchlet error as NSError {
print(error)
}
player?prepareToPlay()
}
override funcdidReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@ IBAction funcplay (sender: UIButton) {
player?play()
}
@ IBAction func pause (sender: UIButton) {
player?.pause()
}
@ IBAction func stop (sender: UIButton) {
player?.stop()
player?currentTime=0
}
}
I'm generating an instance of AVAudioPlayer to play mp3, but I think it's because it's released without being referenced anywhere.
Why don't you correct it as follows?
override func viewDidLoad(){
super.viewDidLoad()
do{
// Corrected stored in local variable
player=try AVAudioPlayer(contentsOfURL:sound_data)
player?play()
}
catchlet error as NSError {
print(error)
}
player?prepareToPlay()
}
© 2024 OneMinuteCode. All rights reserved.