AVAudioPlayer not playing mp3 file - ios

I have run this app on my simulator as well as my phone and with multiple mp3 files however I cannot get sound to output from the app. I have included the mp3 file in the supported files. I am honestly lost as to what to do next. I receive no errors however there is no audio.
#IBAction func play (sender: AnyObject){
func sharedInstance() {
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var audioPlayer = AVAudioPlayer()
var song = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("pingpong", ofType: "mp3")!)
println(song)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: song, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
sharedInstance()
}

Just make your var audioPlayer = AVAudioPlayer() global for your class like shown in below code:
And I have modified your code to make it safe:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
#IBAction func play (sender: AnyObject){
var categoryError: NSError?
if AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &categoryError) {
println("AVAudioSession Category Playback OK")
var activateError: NSError?
if AVAudioSession.sharedInstance().setActive(true, error: &activateError) {
println("AVAudioSession is Active")
var song = NSBundle.mainBundle().URLForResource("we_cant_Stop", withExtension: "mp3")!
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: song, error: &error)
audioPlayer.play()
} else if let activateError = activateError {
println(activateError.description)
}
} else if let categoryError = categoryError {
println(categoryError.description)
}
}
}
This is working fine.

Related

How to fix Thread 1: EXC_BAD_ACCESS (code=1, address=0x58) xcode

I am trying to play some sound files with buttons but pressing the button throws me this error Thread 1: EXC_BAD_ACCESS (code=1, address=0x58) on line
audioPlayer.play()
I have looked for possible solutions and I can't find anything related to that error, the function of my code runs well until the print, this is my complete code.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var track: String? = nil
var audioPlayer = AVAudioPlayer()
#IBAction func heavyButton(_ sender: Any) {
track = "H"
print("heavy machine gun \(track!)")
reproducirAudio(audio: track!)
audioPlayer.play()
}
func reproducirAudio(audio: String) {
do {
print("entro a la funcion de reproducir")
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: audio, ofType: "mp3")!))
audioPlayer.prepareToPlay()
} catch {
print(error)
}
}
}
i found a solution, this is for iOS13
import UIKit
import AVFoundation
class ViewController: UIViewController {
var track: String? = nil
var audioPlayer: AVAudioPlayer?
#IBAction func heavyButton(_ sender: Any) {
track = "H"
print("heavy machine gun \(track!)")
reproducirAudio(audio: track!)
}
func reproducirAudio(audio: String) {
let path = Bundle.main.path(forResource: "\(audio).mp3", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.play()
} catch {
// couldn't load file :(
}
}

AVFoundation - Music iOS

I have been trying to add music to my application without particular success. I have been trying to use AVFoundation and my code is the following:
//MUSIC
var audioPlayer = AVAudioPlayer()
let audioPath = Bundle.main.path(forResource: "happyDays", ofType: "wav")
do {
try audioPlayer = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath!))
}
catch {
// process error
}
audioPlayer.play()
I do not get any error but my application boots and no music plays. Can anyone help?
swift 3
import UIKit
import AVFoundation
class ViewController: UIViewController{
let var avPlayer: AVAudioPlayer!
#IBAction func btnPlayPauseAudio(_ sender: UIButton){
if self.avPlayer != nil{
if let myAudioUrl = Bundle.main.url(forResource: "myAudioFile", withExtension: "mp3"){
if self.avPlayer.isPlaying{
self.avPlayer.pause()
}
else{
self.avPlayer = try AVAudioPlayer(contentsOf: myAudioUrl)
self.avPlayer.prepareToPlay()
self.avPlayer.play()
}
}
}
}
}

Can't play file from documents in AVAudioPlayer

I have a file on documents folder of app and I want to play it.
if NSFileManager.defaultManager().fileExistsAtPath(pathString) {
let url = NSURL(fileURLWithPath:pathString, isDirectory: false)
do {
let player = try AVAudioPlayer(contentsOfURL:url)
player.prepareToPlay()
player.play()
}
catch let error as NSException {
print(error)
}
catch {}
}
There is a file on file system and I checked its existence. Also all lines in do block are executed. There is neither exception nor error and still no sound is played. What are possible problems and how can I solve them?
You should make audioPlayer an instance variable global. This code will have it deallocated immediately after calling .play()
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
if NSFileManager.defaultManager().fileExistsAtPath(pathString){
let url = NSURL(fileURLWithPath:pathString, isDirectory: false)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
}

iOS AVAudioPlayer - how to set file path to the pathForResource

i want to play small mp3 file when button is clicked. but not sure how to set the mp3 file in setPathForResources
Here My Code
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("/sounds/superman", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
#IBOutlet weak var PlaySlow: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func PlaySlowAction(sender: UIButton) {
audioPlayer.play()
}
I have added the sounds folder to the project using just drag and drop. but when i click button im getting this error.
audioPlayer.play() Thread 1: EXC_BAD_ACCESS(Code=1,address=0x1c)
You don't need the sounds/ in your path. Just the filename. e.g.
var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("superman", ofType: "mp3")!)
Also fileURLWithPath takes a URL, not a string. You need to convert your NSBundle.mainBundle().pathForResource("superman", ofType: "mp3") to a string first using NSURL(string:).
This is the full setup:
let path = NSBundle.mainBundle().pathForResource("superman", ofType:"mp3")
let fileURL = NSURL(fileURLWithPath: path)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.delegate = self
player.play()
You missed a couple necessary steps in your "PlaySlowAction" method:
#IBAction func PlaySlowAction(sender: UIButton) {
// if the audioPlayer hasn't been set to any sound file yet,
// load it up...
if(audioPlayer.data == nil)
{
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: &error)
if let actualError = error {
println("An Error Occurred: \(actualError)")
}
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}

Playing a sound with AVAudioPlayer

I'm trying to play a sound with AVAudioPlayer but it won't work.
Edit 1: Still doesn't work.
Edit 2: This code works. My device was in silent mode.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav"))
println(alertSound)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
Made modification to your code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav"))
println(alertSound)
// Removed deprecated use of AVAudioSessionDelegate protocol
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
Swift 3 and Swift 4.1:
import UIKit
import AVFoundation
class ViewController: UIViewController {
private var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "button-09", ofType: "wav")!)
print(alertSound)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
try! audioPlayer = AVAudioPlayer(contentsOf: alertSound)
audioPlayer!.prepareToPlay()
audioPlayer!.play()
}
}
As per Swift 2 the code should be
var audioPlayer : AVAudioPlayer!
func playSound(soundName: String)
{
let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!)
do{
audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)
audioPlayer.prepareToPlay()//there is also an async version
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}
Your audio play will be deallocated right after viewDidLoad finishes since you assign it to a local variable. You need to create a property for it to keep it around.
The solution is for AudioPlayer which has play/pause/stop button in the navigation bar as bar button items
In Swift 2.1 you can use the below code
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let audioPath = NSBundle.mainBundle().pathForResource("ARRehman", ofType: "mp3")
var error:NSError? = nil
do {
player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
}
catch {
print("Something bad happened. Try catching specific errors to narrow things down")
}
}
#IBAction func play(sender: UIBarButtonItem) {
player.play()
}
#IBAction func stop(sender: UIBarButtonItem) {
player.stop()
print(player.currentTime)
player.currentTime = 0
}
#IBAction func pause(sender: UIBarButtonItem) {
player.pause()
}
#IBOutlet weak var sliderval: UISlider!
#IBAction func slidermov(sender: UISlider) {
player.volume = sliderval.value
print(player.volume)
}
}
This will work.....
import UIKit
import AVFoundation
class ViewController: UIViewController {
var ding:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
prepareAudios()
ding.play()
}
func prepareAudios() {
var path = NSBundle.mainBundle().pathForResource("ding", ofType: "mp3")
ding = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!), error: nil)
ding.prepareToPlay()
}
}
Use This Function to make sound in Swift (You can use this function where you want to make sound.)
First Add SpriteKit and AVFoundation Framework.
import SpriteKit
import AVFoundation
func playEffectSound(filename: String){
runAction(SKAction.playSoundFileNamed("\(filename)", waitForCompletion: false))
}// use this function to play sound
playEffectSound("Sound File Name With Extension")
// Example :- playEffectSound("BS_SpiderWeb_CollectEgg_SFX.mp3")
This is a pretty old question, but I did not see an answer that worked with Swift 3.0 so I modernized the code and added some safety checks to prevent crashes.
I also took the approach of pulling the playing part out into its own function to help with re-use for anyone coming across this answer.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
play(for: "button-09", type: "wav")
}
func play(for resource: String, type: String) {
// Prevent a crash in the event that the resource or type is invalid
guard let path = Bundle.main.path(forResource: resource, ofType: type) else { return }
// Convert path to URL for audio player
let sound = URL(fileURLWithPath: path)
do {
audioPlayer = try AVAudioPlayer(contentsOf: sound)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
} catch {
// Create an assertion crash in the event that the app fails to play the sound
assert(false, error.localizedDescription)
}
}
}
Swift 4.2 onwards, AudioSession category setup options have been changed. (Try following code for Swift 4.2 onwards)
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
prepareAudioSession()
}
func prepareAudioSession() -> Void {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
try AVAudioSession.sharedInstance().setActive(true)
prepareAudioPlayer()
} catch {
print("Issue with Audio Session")
}
}
func prepareAudioPlayer() -> Void {
let audioFileName = "test"
let audioFileExtension = "mp3"
guard let filePath = Bundle.main.path(forResource: audioFileName, ofType: audioFileExtension) else {
print("Audio file not found at specified path")
return
}
let alertSound = URL(fileURLWithPath: filePath)
try? audioPlayer = AVAudioPlayer(contentsOf: alertSound)
audioPlayer?.prepareToPlay()
}
func playAudioPlayer() -> Void {
audioPlayer?.play()
}
func pauseAudioPlayer() -> Void {
if audioPlayer?.isPlaying ?? false {
audioPlayer?.pause()
}
}
func stopAudioPlayer() -> Void {
if audioPlayer?.isPlaying ?? false {
audioPlayer?.stop()
}
}
func resetAudioPlayer() -> Void {
stopAudioPlayer()
audioPlayer?.currentTime = 0
playAudioPlayer()
}
}

Resources