Running on device using IPv6 causes app to crash - ios

I tried to submit a sound app for iPad and iPhone (iOS 9.3.5). Then I was told that my play button would not play audio when pressed when connect to a IPv6. This was the code I used to start and stop the sound. It works how I intended when running the simulator.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
var player1 = AVAudioPlayer()
func playsound(sender: AnyObject){
let soundUrl = NSBundle.mainBundle().URLForResource("fsfa", withExtension: "mp3")! // or m4a
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true)
player1 = try AVAudioPlayer(contentsOfURL: soundUrl)
player1.numberOfLoops = -1
player1.prepareToPlay()
player1.play()
} catch _ {
return print("sound file not found")
}
}
func stopsound1(sender: AnyObject){
let soundUrl = NSBundle.mainBundle().URLForResource("dsd", withExtension: "mp3")!
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true)
player1 = try AVAudioPlayer(contentsOfURL: soundUrl)
player1.stop()
} catch _ {
return print("sound file not found")
}
}

Related

Play random sounds from my projects in Swift 5

I'm new in iOS. I have written this code, which plays only one audio file when tapping a UIButton. I would like to play multiple sound randomly. How to set it? Thank you!
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer!
#IBAction func playButtonPressed(_ sender: UIButton) {
if let soundURL = Bundle.main.url(forResource: "kompilacja", withExtension: "mp3") {
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
}
catch {
print(error)
}
audioPlayer.play()
}else{
print("Karwasz twarz! Brak pliku audio, Panie!")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Put all of your sound file names in an array and use the randomElement method to choose your sound.
#IBAction func playButtonPressed(_ sender: UIButton) {
let sounds = ["kompilacja", "another sound", "yet another sound"]
guard let sound = sounds.randomElement(),
let soundURL = Bundle.main.url(forResource: sound, withExtension: "mp3") else { return }
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
}
catch {
print(error)
}
audioPlayer.play()
}

Multiple Audio Files In One ViewController With Button

Want to play multiple audio files in the same ViewController. When a user clicks on Button1 the file1.mp3 should be loaded into ViewController and when user hit play same should play and for button2 file2.mp3 should load and play.
I know how to do this for a single file but for multiple files I have to create ViewController again and again which is so hard. This is my code for single file
#IBAction func buttonPressed(_ sender: UIButton) {
if player.isPlaying {
player.stop()
sender.setImage(UIImage(named:"play.png"),for: .normal)
} else {
player.delegate = self
player.play()
player.numberOfLoops = 107
sender.setImage(UIImage(named:"pause.png"),for: .normal)
}
}
do {
let audioPlayer = Bundle.main.path(forResource: "chalisa", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPlayer!) as URL)
}catch {
//ERROR
}
You can use Tableview List all songs Name and Play Button use to Multiple audio files use in one viewcontroller
import AVFoundation
//MARK:- Variable Declaration
var player: AVAudioPlayer?
func playMusic() {
guard let url = Bundle.main.url(forResource: "chalisa", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
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)
}
}

Playing sounds with multiple play buttons in iOS

I have to play three types of wav file one at a time. When I click on the Play button in Enter region it plays a sound named "EnterRegion.wav" and clicking on Exit Region play button plays "ExitRegion.wav" audio file.
But for the play button of the Immediate, it plays a sound repeatedly until I press the Stop button.
Both first and second Play buttons are working perfectly for me but when I click on play button in Immediate, it plays sound for the first time but when I click on other play buttons and come back to Immediate play button again, the application throws exceptions. This happens the same when I press stop button and come back to the play button of immediate section. My sample app screenshot and code sample which is in Swift 4 is as below.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var engine: AVAudioEngine!
var enterWavFile: AVAudioFile!
var audioPlayerNode : AVAudioPlayerNode!
var immediaAudioPlayerNode: AVAudioPlayerNode!
var exitWavFile: AVAudioFile!
var flatlineWavFile:AVAudioFile!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
engine = AVAudioEngine()
enterWavFile = try? AVAudioFile(forReading: NSURL.fileURL(withPath:
Bundle.main.path(forResource: "EnterRegion", ofType: "wav")!))
exitWavFile = try? AVAudioFile(forReading: NSURL.fileURL(withPath:
Bundle.main.path(forResource: "ExitRegion", ofType: "wav")!))
flatlineWavFile = try? AVAudioFile(forReading: NSURL.fileURL(withPath:
Bundle.main.path(forResource: "Immediate", ofType: "wav")!))
}
#IBAction func playEnterRegionSound(_ sender: UIButton) {
playSound(audioFile: enterWavFile)
}
#IBAction func playExitRegion(_ sender: UIButton) {
playSound(audioFile: exitWavFile)
}
func playSound(audioFile: AVAudioFile) {
audioPlayerNode = AVAudioPlayerNode()
if(audioPlayerNode.isPlaying){
audioPlayerNode.stop()
}
if(engine.isRunning){
engine.stop()
engine.reset()
}
engine.attach(audioPlayerNode)
engine.connect(audioPlayerNode, to: engine.mainMixerNode, format: audioFile.processingFormat)
audioPlayerNode.scheduleFile(audioFile, at: nil, completionHandler: nil)
// Start the audio engine
engine.prepare()
try! engine.start()
audioPlayerNode.play()
}
#IBAction func playImmediateFlatline(_ sender: UIButton) {
immediaAudioPlayerNode = AVAudioPlayerNode()
if(immediaAudioPlayerNode.isPlaying){
print("immediateAudioPlayerNode Playing")
immediaAudioPlayerNode.stop()
}
if(engine.isRunning){
print("engine Running")
engine.stop()
engine.reset()
}
let audioFileBuffer = AVAudioPCMBuffer(pcmFormat: flatlineWavFile.processingFormat, frameCapacity: AVAudioFrameCount( flatlineWavFile.length))!
try? flatlineWavFile.read(into: audioFileBuffer)
engine.attach(immediaAudioPlayerNode)
engine.connect(immediaAudioPlayerNode, to: engine.mainMixerNode, format: flatlineWavFile.processingFormat)
immediaAudioPlayerNode.scheduleBuffer(audioFileBuffer, at: nil, options: AVAudioPlayerNodeBufferOptions.loops, completionHandler: nil)
// Start the audio engine
engine.prepare()
try! engine.start()
immediaAudioPlayerNode.play()
}
#IBAction func stopImmediateFlatline(_ sender: UIButton) {
if (immediaAudioPlayerNode.isPlaying){
print("immediateAudioPlayerNode playing")
immediaAudioPlayerNode.pause()
}
if(engine.isRunning){
print("engine Running")
engine.stop()
engine.reset()
}
}
}
I am unable to locate why this is happening and could you please help me to fix the issue or any suggestions.
code for playing the sound
var player1: AVAudioPlayer?
var player2: AVAudioPlayer?
var player3: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "Music", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
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 }
// read this line of code for you to play the wav file you wanted to play ang then trigger it using a button.
player.play()
} catch let error {
print(error.localizedDescription)
}
}

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()
}
}
}
}
}

Swift 2 - AVAudioPlayer not playing audio

I'm trying to play a sound with an AVAudioPlayer, but it doesn't play. I tried both a device (iPhone 6s) and the simulator. I'm not getting any errors and it logs it played. When I set a breakpoint before audioPlayer.play() and step over it plays for a few seconds and stops then. My code:
let soundURL = NSBundle.mainBundle().URLForResource("test", withExtension: "mp3")
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
if let soundURL = soundURL {
let audioPlayer = try AVAudioPlayer(contentsOfURL: soundURL)
audioPlayer.volume = 1
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
print(audioPlayer.duration)
audioPlayer.play()
print("PLAYED")
}
}catch {
print("Error getting the audio file")
}
Here is an example that will work. I am not sure where, in relation to the rest of your code, you have the code that you've shown above. Make sure your device volume is not on silent and is turned up...
//declare these as instance variables
var AudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("FileName", ofType: "mp3")!)
var AudioPlayer = AVAudioPlayer()
//inside viewDidLoad establish your AVAudioSession and configure the AudioPlayer with the contents of URL
override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
//print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
//print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
do {
try AudioPlayer = AVAudioPlayer(contentsOfURL: AudioURL, fileTypeHint: nil)
} catch {
print("errorin do-try-catch")
}
}
//play audio
#IBAction func playAudio(sender: AnyObject){
AudioPlayer.play()
}

Resources