Play multiple songs in iOS - ios

I wrote this code for iOS to play a song, however I'm not sure how to write the code to play multiple songs.
This is the line of code for a song:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player:AVAudioPlayer = AVAudioPlayer()
#IBAction func play(_ sender: AnyObject)
{
player.play()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do
{
let audioPath = Bundle.main.path(forResource: "Ken", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch
{
//ERROR
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

You actually can play it with just two instances of the AVAudioPlayer resp. every sound file needs it's own AVAudioPlayer if you want to play them simultaneously.

I already wrote an answer, so I will post even there is already a correct answer. What palme said is correct. You could use multiple AVAudioPlayer instances to play multiple sounds simultaneously:
import UIKit
import AVFoundation
class ViewController: UIViewController {
let paths = ["a","b"]
var sounds = [AVAudioPlayer]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for path in paths {
do
{
let audioPath = Bundle.main.path(forResource: path, ofType: "mp3")
let player = try AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
sounds.append(player)
}
catch
{
//ERROR
}
}
for sound in sounds {
sound.play()
}
}
}

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

Can't stop AVFoundation song

I'm making a game with level selection in Swift 3.0, and I'm using AVFoundation to play background music. I'd like to play a different song for every level, however when I try to stop the song and play a new one after I've beaten the level, instead of stopping it it just replays it. Here's my code, seriously been working on this for hours and gotten no where.
import UIKit
import AVFoundation
class LevelSelect: UIViewController {
var AudioPlayer0 = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let AssortedMusics0 = NSURL(fileURLWithPath: Bundle.main.path(forResource: "Background", ofType: "mp3")!)
AudioPlayer0 = try! AVAudioPlayer(contentsOf: AssortedMusics0 as URL)
AudioPlayer0.prepareToPlay()
AudioPlayer0.numberOfLoops = -1
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func Level0Button(_ sender: Any) {
AudioPlayer0.stop()
AudioPlayer0.play()
}
}
Thanks for the help!

Swift 3 - AVAudioPlayer is not playing sound

I have a simple program which has one button and its only function is to trigger an sound output.
The app works perfectly when tested on an iOS simulator, but when I test it on an iPhone, the app is not playing any sound. I have tested this on two iPhones.
This was working once upon a time. I don't know if updating to iOS 10 has caused the issue.
Here is my code:
//Code
import UIKit
import AVFoundation
var audioPlayer = AVAudioPlayer()
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let music = Bundle.main.path(forResource: "sound", ofType: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! ))
}
catch{
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playSound(_ sender: UIButton) {
audioPlayer.play()
}
}
Would be grateful for any answers.
Thanks.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let music = Bundle.main.path(forResource: "sound", ofType: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! ))
audioPlayer.delegate = self
audioPlayer.preparedToPlay()
}
catch{
print(error)
}
}
import UIKit
import AVFoundation
class ViewController: UIViewController {
var btnSound: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
//locate resource
let path = Bundle.main.path(forResource: "sound", ofType: "wav")
let music = URL(fileURLWithPath: path!)
do{
try btnSound = AVAudioPlayer(contentsOf: music)
btnSound.prepareToPlay()
} catch let err as NSError{
print(err.debugDescription)
}
}
}
func playSound(){
if btnSound.isPlaying{
//stop playing sound file if already playing
btnSound.stop()
}
//play sound
btnSound.play()
}
#IBAction func playSound(sender: UIButton){
//call playSound function on pressing the button you attach this function to
playSound()
}

Create a random audio sound generator

Thanks for replying.
I am trying to make a program when I press a button once, two random sounds will play. I can get the random sounds to play if I press the button, but I am looking that if I press the button, the random sound will play differently each time.
I can paste the sounds together to hear them in the sequence I want them, but I would like swift to generate the sounds.
I thought of the AVqueplayer to make it as a playlist. I was thinking this can be like a pair of dice in an analogy. For example, if I were to throw the dice down, the random sounds will occur.
I am still a newbie, and tried to figure this out on my own, because it seemed so simple, but I am out of options now.
Here is what I got so far. This will play a random sound when I press the button each time.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer = AVAudioPlayer()
var sounds = ["sound1", "sound2", "sound3"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if event!.subtype == UIEventSubtype.motionShake {
let randomNumber = Int(arc4random_uniform(UInt32(sounds.count)))
let fileLocation = Bundle.main.path(forResource: sounds[randomNumber], ofType: "mp3")
var error: NSError? = nil
do { try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!))
player.play()
} catch {}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Using the same code, and adding a second random number with matching file location will allow the sounds to play back to back, both being random:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer = AVAudioPlayer()
var sounds = ["sound1", "sound2", "sound3"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if event!.subtype == UIEventSubtype.motionShake {
let randomNumber1 = Int(arc4random_uniform(UInt32(sounds.count)))
let randomNumber2 = Int(arc4random_uniform(UInt32(sounds.count)))
let fileLocation1 = Bundle.main.path(forResource: sounds[randomNumber1], ofType: "mp3")
let fileLocation2 = Bundle.main.path(forResource: sounds[randomNumber2], ofType: "mp3")
//var error: NSError? = nil
do {
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation1!))
player.play()
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation2!))
player.play()
} catch {}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

How do I play a video inside view controller with Swift 2 - 'If let' Error

I have imported both mediaPlayer and AVfoundation
class AuroraViewController: UIViewController {
var moviePlayer: AVPlayer?
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.
}
private func playVideo() {
if let
path = NSBundle.mainBundle().pathForResource("Aurora", ofType:"mp4"),
url = NSURL(fileURLWithPath: path),
moviePlayer = AVPlayer(contentURL: url) {
self.moviePlayer = moviePlayer
moviePlayer.view.frame = self.view.bounds
moviePlayer.prepareToPlay()
moviePlayer.scalingMode = .AspectFill
self.view.addSubview(moviePlayer.view)
} else {
debugPrint("oops, something wrong when playing video.m4v")
}
}
I Get an error about the 'if let': Initializer for conditional binding must have Optional type, not 'NSURL'. Is there a different way to do this?
UPDATE Correct code:
import UIKit
import AVFoundation
import AVKit
class myClass: AVPlayerViewController {
private func playVideo() {
if let path = NSBundle.mainBundle().pathForResource("Video Name", ofType: "mp4") {
let url = NSURL(fileURLWithPath: path)
player = AVPlayer(URL: url)
}
else {
print("Oops, something wrong when playing video.m4v")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
}
Hope this helps.
You can only use "if let" for optional values:
if let nonoptional = optional {
}
If the right hand side is not optional, then the if let is just unnecessary.
The url is not an optional,after you got the path you are sure that there is something and the url is not an optional because there you can have an url where the file doesn't exists, but now you are sure that the file exists because you done if let with the path . Try this
private func playVideo() {
if let path = NSBundle.mainBundle().pathForResource("Video Name", ofType: "mp4") {
let url = NSURL(fileURLWithPath: path)
player = AVPlayer(URL: url)
player?.play()
}
else {
print("Oops, something wrong when playing video.m4v")
}
}

Resources