AVAudioPlayer is not playing in swift. How to fix it? - swift

In my app I want to integrate a AVAudioPlayer in my app. But I can`t here anything.
Thats my code:
import UIKit
import AVFoundation
class NotenAnsicht: UIViewController{
var PlaybackPlayer:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
PlaybackAudioAufsetzen()
}
func PlaybackAudioAufsetzen(){
do{
let audioPath = Bundle.main.path(forResource: "song", ofType: "mp3")
try PlaybackPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
print("Song set")
}
catch{
print("there was an Error")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#objc func PlaybayStarten(sender:UIButton){
PlaybackPlayer.play()
PlaybackPlayer.volume = 1
print(PlaybackPlayer.isPlaying)
print("Song should play")
}
}
I have no idea where the problem is. All functions get called properly. And the audioplayer is not defined locally. After PlaybackPlayer.play(), PlaybackPlayer.isPlaying returns true. I just can`t here anything.
Do you have any idea where the problem is?

set try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) and try AVAudioSession.sharedInstance().setActive(true) in your do block before setting audioPath.
your code should be look like that.
func PlaybackAudioAufsetzen(){
do{
let audioPath = Bundle.main.path(forResource: "song", ofType: "mp3")
/// this code will make this app ready to takeover the device audio
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try PlaybackPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
print("Song set")
}
catch let error {
print(error.localizedDescription)
}
}

Related

Swift 4 / Xcode 9.2 - Audio Player

For playing back audio I went through a bigger post here. Resulting in the best version now, but:
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
does not work, giving a String member error on .playback. HereĀ“s the full code:
import Foundation
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
#IBAction func triggerSample(_ sender: Any) {
playSound()
}
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
UPDATE: The solution is written in the commented out sections above: Regarding this, use the following playSound()for Xcode 9.2:
func playSound() {
guard let url = Bundle.main.url(forResource: "MWSTW_Bowie", withExtension: "mp3") else { return }
do {
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
} //end of do/catch
} // end of playSound()
That works just fine. Just make sure you have an MP3 in the App bundle named "soundName" of type .mp3

Swift Sound Effects // Why Won't My Code Work?

I have been trying to make a game to teach myself swift, and cant seem to get this code to work. I am extremely new to this, and can't seem to find out why it won't work... XCode doesn't flag any problems, build sucseed, and debugger even prints "Got to Stage 1 & Got to Stage 2... anything help?
I Imported AVFoundation..
class GAME {
class func SuperStartGame(playerwhowon1: SKSpriteNode) {
var player = AVAudioPlayer()
func PlaySound() {
guard let URL = Bundle.main.url(forResource: "PowerUp", withExtension: "mp3")
else {
print("Didn't Find URL")
return
}
do {
print("Got to Stage 1")
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: URL, fileTypeHint: "mp3")
player.prepareToPlay()
player.play()
print("Got to Stage 2")
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
RoundNumber += 1
Round.text = "Round \(RoundNumber)"
if playerwhowon1 == Mine {
MyScore.run(addscoreM) {
PlaySound()
Round.run(NewRoundForRound) {
...
Code keeps going.. thats the only part that is relevant to the sound. I added the sound file to Xcode, and made sure it was added tot he project target... it is in my main bundle.
Make sure that your device isn't muted
mp3 file is copied to bundle
Example VC playing sound:
class ViewController: UIViewController {
var game = Game()
#IBAction func playAction(_ sender: UIButton) {
game.playSound()
}
}
class Game {
var player: AVAudioPlayer?
func playSound() {
guard let URL = Bundle.main.url(forResource: "SampleAudio", withExtension: "mp3") else {
print("Didn't Find URL")
return
}
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: URL, fileTypeHint: "mp3")
player?.prepareToPlay()
player?.play()
} catch let error as NSError {
print("\(error.localizedDescription)")
}
}
}

Does anybody know how to fix Do-Try-Catch error code= EXC_1386_INVOP in swift?

I'm writing calculator app in swift when I tried to add audio file I put this above the calc programming:
var player:AVAudioPlayer = AVAudioPlayer()
#IBAction func play(_ sender: UIButton)
{
player.play()
}
and down below in view did load I put this. Please, any help will be great!
override func viewDidLoad() {
super.viewDidLoad()
//Do any additional setup after loading the view, typically from a nib.
do
{
let audioPath = Bundle.main.path(forResource: "song", ofType: "mp4")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch
{
// error
abort()
}
}
you are retreiving path Not the URL... secondly your do try Syntax is wrong... try this code
do
{
let audioPath = Bundle.main.url(forResource: "song", withExtension: "mp4")
player = try AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch
{

Create a function from code

How do I create a function from this code in swift3?
I have a button which is pressed then plays this sound "push"
How can it be simplified when there are lots of buttons? I don't want to add all codes to every button.
var myAudio = AVAudioPlayer()
// Add sound
do {
try myAudio = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath:
Bundle.main.path(forResource: "push", ofType: "mp3")!) as URL)
} catch {
NSLog("No file!")
}
//call the sound
myAudio.play()
I made this change
func play(name : String){
do {
try myAudio = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath:
Bundle.main.path(forResource: name, ofType: "mp3")!) as URL)
} catch {
NSLog("No file!")
}
}
#IBAction func buttonFirst(_ sender: UIButton) {
play(name: "push")
myAudio.play()
}
#IBAction func buttonSecond(_ sender: UIButton) {
play(name: "second")
myAudio.play()
}
I got this output:
2017-07-25 16:13:23.270349+0100 sound[1728:933024] [aqme] 254: AQDefaultDevice (173): skipping input stream 0 0 0x0
Is that a problem?
I think you forgot the prepare
var audioPlayer = AVAudioPlayer()
let sound = URL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "mp3")!)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
try! audioPlayer = AVAudioPlayer(contentsOf: sound)
audioPlayer.prepareToPlay()
audioPlayer.play()
You can use it in the following way
var myAudio : AVAudioPlayer?
func playSound(){
let path = Bundle.main.path(forResource: "push", ofType:"mp3")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
self.myAudio = sound
sound.numberOfLoops = 1
sound.prepareToPlay()
sound.play()
} catch {
print("error loading file")
// couldn't load file :(
}
}
Furthermore you can use SwiftySound that lets you play sounds easily in Swift 3.
for example
Sound.play(file: "push.mp3")

Swift 3: stream MP3 file from server

I am trying to stream a sample mp3 from a url. It is a very small sample file. However, when I press the play button nothing happens. Well, no sound plays.
I am rather new to Swift and very much a noob so here is the full View Controller as I am unsure what you might need.
import UIKit
import AVKit
import AVFoundation
import Foundation
class ViewController: UIViewController {
#IBAction func playButton(_ sender: Any) {
print("pressed")
let urlstring = "http://cdn.mos.musicradar.com/audio/samples/80s-heat-demos/AM_Eighties08_85-01.mp3"
let url = NSURL(string: urlstring)
print("the url = \(url!)")
downloadFileFromURL(url: url!)
}
override func viewDidLoad() {
// Do any additional setup after loading the view
}
func downloadFileFromURL(url:NSURL){
weak var weakSelf = self
var downloadTask:URLSessionDownloadTask
downloadTask = URLSession.shared.downloadTask(with: url as URL, completionHandler: { (URL, response, error) -> Void in
print("URL = \(URL)")
weakSelf!.plays(url: URL! as URL)
})
downloadTask.resume()
}
func plays(url:URL) {
print("playing \(url)")
do {
var playerItem = AVPlayerItem(url: url as URL)
player = AVPlayer(url : url)
player.volume = 1.0
player.play()
} catch let error as NSError {
print(error.localizedDescription)
} catch {
print("AVAudioPlayer init failed")
}
}
}
in my console I am getting this:
pressed
the url = http://cdn.mos.musicradar.com/audio/samples/80s-heat-demos/AM_Eighties08_85-01.mp3
URL = Optional(file:///private/var/mobile/Containers/Data/Application/C255E8F4-DDBA-43BB-BC33-AF71C08BBDFD/tmp/CFNetworkDownload_tm0O8v.tmp)
playing file:///private/var/mobile/Containers/Data/Application/C255E8F4-DDBA-43BB-BC33-AF71C08BBDFD/tmp/CFNetworkDownload_tm0O8v.tmp
URL = Optional(file:///private/var/mobile/Containers/Data/Application/C255E8F4-DDBA-43BB-BC33-AF71C08BBDFD/tmp/CFNetworkDownload_J1f2LF.tmp)
playing file:///private/var/mobile/Containers/Data/Application/C255E8F4-DDBA-43BB-BC33-AF71C08BBDFD/tmp/CFNetworkDownload_J1f2LF.tmp
Can anyone help me solve this? I just want to be able to play this sound on click of the button from the server not locally.
Please try to use this code for you player function.
func plays(url:URL) {
print("playing \(url)")
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.play()
} catch let error as NSError {
print(error.localizedDescription)
} catch {
print("AVAudioPlayer init failed")
}
}