I am currently playing an audio file with "MobileVlcKit" and I need to switch to earSpeaker (top speaker for phone calls) in the middle of playing audio file.
Currently I am using this code:
AVAudioSession.sharedInstance().overrideOutputAudioPort(.none)
But it keep playing from main speaker.
Do anyone knows what is my problem?
I just checked my 2 years old objective-c code, not sure will it work for you, but worth to try. here is its swift version:
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(false)
try audioSession.setCategory(.playAndRecord, options: .defaultToSpeaker)
try audioSession.overrideOutputAudioPort(.none)
try audioSession.setActive(true)
} catch {
// handle error
print(error)
}
Related
I have an iOS app using SwiftUI. It handles a few sound files and performs some audio recording. This is the function doing the recording work:
func recordAudio(to file: String, for duration: TimeInterval) {
let audioSession:AVAudioSession = AVAudioSession.sharedInstance()
do {try audioSession.setCategory(.playAndRecord, mode: .default)
try audioSession.setActive(true)
let audioFilename = getDocumentsDirectory().appendingPathComponent(file+".m4a"),
audioURL = URL(fileURLWithPath: audioFilename),
settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
audioRecorder = try AVAudioRecorder(url: audioURL, settings: settings)
audioRecorder.delegate = self
audioRecorder.record(forDuration: TimeInterval(2.0))
} catch let error as NSError {
print("Failed -- Recording !!! -> \(error)")
}
}
At this point, it basically works, but there is a strange behaviour that I neither understand nor like.
Here is the problem:
When I start the app and play a sound file, the volume is right for my taste.
Then without ever adjusting the volume I perform some recording (using the function above).
Finally after the recording is done, I go back to the file I played just before and play it again; the volume has mysteriously gone down, without me knowing why.
Is there something in my function that could explain that?
Or some other cause that someone could think of?
If I restart the app, the volume automatically goes back to normal.
For information, I am using iOS 14.4.2 and Xcode 12.4.
The audio session will be a decreased volume during playback after recording in .playAndRecord mode. After recording, explicitly set to something like .playback to get the volume you're expecting.
I have an iPhone app that plays back prerecorded video clips. The audio sounds fine from the phone speaker or applepods, but when I listen through bluetooth connected headphones/speakers that are not apple it sounds terribly distorted. I have tried to use AVAUDIOSESESSION to fix the problem, but no luck. This is the code I tried (from another similar stack overflow answer):
var error: NSError?
var success: Bool?
override func viewDidLoad() {
super.viewDidLoad()
// so we can play the audio undistorted through bluetooth headphones:
do {
try AVAudioSession.sharedInstance().setCategory(.playAndRecord,
mode: .default, options: [.mixWithOthers, .allowAirPlay,
.allowBluetoothA2DP,.defaultToSpeaker])
try AVAudioSession.sharedInstance().setActive(true)
} catch let error1 as NSError {
error = error1
success = false
}
if !success! {
print("Failed to set audio session category. Error: \(error!)")
}
I am a first time developer so I need things explained very simply and from the basics up. Thank you so much.
It was an embarrassing error. I hope no one else makes it.
The range of AVPlayer's volume must be between 0.0 and 1.0. If you set the volume louder than this (I had player.volume = 7, instead of player.volume = 0.7) you will get distortion on non-apple bluetooth headphones for some reason (apple earphones and the internal speaker accommodates for this error).
I am successfully able to use Speech (speech recognition) and I can use AVFoundation to play wav files in Xcode 8/IOS 10. I just can't use them both together. I have working speech recognition code where I import Speech. When I import AVFoundation into the same app and use the following code, there is no sound and no errors are generated:
var audioPlayer: AVAudioPlayer!
func playAudio() {
let path = Bundle.main.path(forResource: "file.wav", ofType: nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
audioPlayer = sound
sound.play()
} catch {
//handle error
}
}
I assume it is because both use audio. Can anyone suggest how to use both in the same app? I also find that I cannot use speech recognition and text-to-speech together in the same app.
I just bumped into the same problem, and here is how I solved,
add the following line when Speech Recognition is done. What it does is basically setting the audio session back to AVAudioSessionCategoryPlayback category.
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
try audioSession.setActive(false, with: .notifyOthersOnDeactivation)
} catch {
// handle errors
}
hope it helps.
You should change this line:
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
on to:
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
This should work ;-)
It seems that AVAudioPlayer stops playing the sample if you're using AVAudioSession to record the microphone as in Apple's speech recognition example.
However, I've managed to circumvent this by using AVCaptureSession to capture audio as described in this answer.
I am trying to play background music on an app I am creating, but none of the solutions I have seen online work. I have experimented with about 5 different blocks of code that others said worked for them but have been short of success on all the attempts. My current code is down below(it is also not working even though there are no errors), I would greatly appreciate it if anyone could give me an explanation as to what I am doing wrong. Thanks!
func playBackgroundMusic() {
do {
self.audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("cool_song", ofType: "mp3")!))
self.audioPlayer.play()
} catch {
print("Error")
}
}
I'm using the following code to play a sound off a URL from the internet:
var audioPlayer = AVPlayer()
...
let audioSession = AVAudioSession.sharedInstance()
audioSession.setCategory(AVAudioSessionCategoryAmbient, error: nil)
let url = trackFileName
let playerItem = AVPlayerItem( URL:NSURL( string:url ) )
audioPlayer = AVPlayer(playerItem:playerItem)
audioPlayer.rate = 1.0;
player.play()
I'm trying to make sure it keeps playing in the background which is the reason why I'm using "AVAudioSession.sharedInstance()". When I try it out in the simulator by locking the screen, it keeps playing like it's supposed to. But if I play it in a device, the sounds shuts off as soon as the screen looks itself automatically or I lock it myself.
What am I missing in my code?
swift 2+ solution:
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
return print("error")
}
Open your app info.plist as Source code (to edit in text mode) and add the following just after dict:
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
You use wrong category, for AVAudioSessionCategoryAmbient it's normal behavior "Your audio is silenced by screen locking and by the Silent switch".
Use AVAudioSessionCategoryPlayback instead.
first of all you should add background mode to your plist like this:
Then you should use AVAudioSessionCategoryPlayback session. Like this:
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSessionCategoryAmbient does not work in background.