Setup AVAudioPlayer with swift 1.2? - swift

When I tried to setup AVaudioPlayer last time, I used this code:
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
var path = NSBundle.mainBundle().pathForResource(file, ofType:type)
var url = NSURL.fileURLWithPath(path!)
var error: NSError?
var audioPlayer:AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
return audioPlayer!
}
var buttonBeep = AVAudioPlayer()
buttonBeep = self.setupAudioPlayerWithFile("buttonPush", type:"m4a")
And it worked perfectly. Now with Swift 1.2 it seems that I can't do that.
I also tried this code:
var button : AVAudioPlayer?
in didMoveToView:
if let button = self.setupAudioPlayerWithFile("button", type:"m4a") {
self.button = button
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer? {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
var error: NSError?
var audioPlayer:AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
return audioPlayer
}
It gives me an error on let url line - EXC_BAD_INSTRUCTION. I put my audio file in Supporting Files inside my project. What am I doing wrong?
UPDATE: that was my mistake. If you have the same problem — make sure you are adding sounds to a target of your app, not just in project

Try this code:
var backgroundMusicPlayer: AVAudioPlayer!
func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if (url == nil) {
println("Could not find file: \(filename)")
return
}
var error: NSError? = nil
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
if backgroundMusicPlayer == nil {
println("Could not create audio player: \(error!)")
return
}
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
}
Use it this way:
playBackgroundMusic("button.m4a")
Hope it helps.
It was working fine with 1.2 and I didn't test it right now because I have updated my Xcode and I suggest you to use latest version of Xcode which have swift version 2.0.

Related

Cannot assign value of type AVAudioPlayer Swift

I am trying to trigger a function when a song finishes playing. Here is my audio player class:
import AVFoundation
public class SKTAudio {
public var backgroundMusicPlayer: AVAudioPlayer?
public func playBackgroundMusic(filename: String) {
let url = Bundle.main.url(forResource: filename, withExtension: nil)
if (url == nil) {
print("Could not find file: \(filename)")
return
}
var error: NSError? = nil
do {
backgroundMusicPlayer = try AVAudioPlayer(contentsOf: url!)
} catch let error1 as NSError {
error = error1
backgroundMusicPlayer = nil
}
if let player = backgroundMusicPlayer {
player.delegate = self
player.prepareToPlay()
player.play()
} else {
print("Could not create audio player: \(error!)")
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer,
// Do stuff
}
}
However, the code won't compile, and the line player.delegate = self returns this error:
Cannot assign value of type 'SKTAudio' to type
'AVAudioPlayerDelegate?'
And gives the option to:
Insert ' as! AVAudioPlayerDelegate'
This compiles, but, upon running, crashes and returns the following in console:
Could not cast value of type 'Scene.SKTAudio' (0x102ebf7b0) to
'AVAudioPlayerDelegate'
Where playBackgroundMusic() is called within Scene. I have no clue what to do at this point, I've tried to follow various other posts but nobody seems to face an issue with the player.delegate = self line. Thank you

AVAudioPlayer not working anymore

This program was working before and I do not believe I changed anything. Here is the code. I get the thrown error : file not found: bgMusic
import SpriteKit
import AVFoundation
class GameScene: SKScene, SKPhysicsContactDelegate {
var backgroundMusicPlayer = AVAudioPlayer()
func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
guard let newURL = url else {
print("Could not find file: \(filename)")
return
}
do {
backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
} catch let error as NSError {
print(error.description)
}
}
override init(size: CGSize) {
super.init(size: size)
playBackgroundMusic("bgMusic")
}
Try getting the file path instead. This works for me everytime.
//Change 'ofType' to whatever the file type is. (.m4a, .mp3, etc.)
let path = NSBundle.mainBundle().pathForResource(filename, ofType: ".mp3")
let url = NSURL.fileURLWithPath(path!)
Then load the url into the AVAudioPlayer.
If that doesn't work, then make sure the filename is correct and that it is added into your project. Best of luck!

fatal error: unexpectedly found nil while unwrapping an Optional value when using AudioPlayer in Swift 2

Hi I am trying to play a music file with a following code in swift 2. Basically I just dragged the audio file with a name f.mp3 to the asses folder and it my code breaks with the following message:
unexpectedly found nil while unwrapping an Optional value. Where exactly I need to put my mp3 file so the IOS can find it. Thank you
var audioPlayer: AVAudioPlayer! = nil
func playMyFile() {
let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3")
let fileURL = NSURL(fileURLWithPath: path)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: fileURL)
} catch {
print("error")
}
audioPlayer.prepareToPlay()
audioPlayer.delegate = self
audioPlayer.play()
}
Your code is working fine with my project and here is my complete code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer! = nil
override func viewDidLoad() {
super.viewDidLoad()
playMyFile()
}
func playMyFile() {
let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3")
let fileURL = NSURL(fileURLWithPath: path!)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: fileURL)
} catch {
print("error")
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
Make sure your audio is added into Copy Bundle Resources like this:
If not added then add it this way:
Check THIS sample for more Info.

fatal error: unexpectedly found nil while unwrapping

why I am getting Thread 1:EXE_BAD_INSTRUCTION
this is my code
override func viewDidAppear(animated: Bool) {
var fileclocaiton = NSString(string: NSBundle.mainBundle().pathForResource(self.navigationItem.title, ofType: "mp3")!)
var error: NSError? = nil
player = AVAudioPlayer(contentsOfURL: NSURL(string: fileclocaiton as String), error: &error)
}
var fileclocaiton = NSString(string: NSBundle.mainBundle().pathForResource(self.navigationItem.title, ofType: "mp3")!)
This line is the source of crash. Are you sure that you have the same resource as your navigationItem.title is ? Is navigationItem.title same as title property on UIViewController ? That you have to try out and make sure that the resource of that type exist. You could avoid crash in case the resource is not found using if let as,
if let fileclocaiton = NSString(string: NSBundle.mainBundle().pathForResource(self.navigationItem.title, ofType: "mp3")) {
... do rest of your coding here.
}

Issue with downloading youtube videos with swift

I am trying to download youtube video in my app and for that I used THIS and library included in that answer but my app is crashing with error :
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is my swift code:
import UIKit
class ViewController: UIViewController {
let videoID = "hS5CfP8n_js"
var extractor = LBYouTubeExtractor()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func start(sender: AnyObject) {
var url: String = "https://www.youtube.com/watch?v=hS5CfP8n_js"
let testURL = NSURL(string:url)
if testURL != nil {
extractor = LBYouTubeExtractor(URL: testURL, quality: LBYouTubeVideoQualityLarge)
extractor.extractVideoURLWithCompletionBlock({(videoURL, error) in
if error == nil {
println(videoURL)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let data = NSData(contentsOfURL: videoURL)!
let pathToDocs = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let fileName = "video_\(self.videoID).mp4"
let yourPath = pathToDocs.stringByAppendingPathComponent(fileName)
data.writeToFile(yourPath, atomically: true)
println("File \(fileName) successfully saved")
})
} else {
println("Failed extracting video URL using block due to error:\(error)")
}
})
}
}
}
my project is crashing at this line:
let data = NSData(contentsOfURL: videoURL)!
But I can get videoURL in console:
http%3A%2F%2Fr3---sn-tv0cgv5qc5oq-nu8e.googlevideo.com%2Fvideoplayback%3Fsver%3D3%26id%3D852e427cff27fe3b%26dur%3D55.681
... ty=small
I don't know what I am missing.
Here is my sample project.