Playing Back Audio Using Avaudioplayer iOS 7

Playing back audio using AVAudioPlayer iOS 7

You're having an ARC issue here. myPlayer is being cleaned up when it's out of scope. Create a strong property, assign the AVAudioPlayer and you're probably all set!

@property(nonatomic, strong) AVAudioPlayer *myPlayer;

...

// create new audio player
self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
[self.myPlayer play];

AVAudioRecorder & AVAudioPlayer with iOS 7 not working properly

I was having the same issue... It appears as if Apple is now requiring the use of AVAudioSession prior to using the AVAudioRecorder. I couldn't find any documentation on this change in requirement, however the recording portion of my app is now working.

All I did was create an audioSession, set the category, and set it to be active. I did this prior to calling prepareToRecord and I tried it after the call to prepareToRecord... both ways worked.

I hope this fixes your problem!

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];

iOS 7 : simple audio controls with AVAudioPlayer?

Use a UISlider with AVAudioPlayer's playAtTime: Method, there is no built-in seek bar for AVAudioPlayer.

Check out this sample code, it implements what you want in the class avTouchController

https://developer.apple.com/library/ios/samplecode/avTouch/Introduction/Intro.html

add a UISLider to you interface and link the valueChanged: to the method seekTime:

in .h

@property (nonatomic, weak) IBOutlet UISlider *seekbar;

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

@property (nonatomic, strong) NSTimer *updateTimer;

in .m in viewDidLoad after loading AVAudioPlayer,

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"There's A Long, Long Trail A-Winding" ofType:@"mp3"]];

AVAudioPlayer *audio = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];

self.audioPlayer = audio;

self.seekbar.minimumValue = 0;

self.seekbar.maximumValue = self.audioPlayer.duration;

[[self audioPlayer] play];

self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateSeekBar) userInfo:nil repeats:YES]

and add the following method

- (void)updateSeekBar{
float progress = self.audioPlayer.currentTime;
[self.seekbar setValue:progress];
}

- (IBAction)seekTime:(id)sender {

self.audioPlayer.currentTime = self.seekbar.value;

}

How to play a sound using Swift?

Most preferably you might want to use AVFoundation.
It provides all the essentials for working with audiovisual media.

Update: Compatible with Swift 2, Swift 3 and Swift 4 as suggested by some of you in the comments.


Swift 2.3

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
let url = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!

do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }

player.prepareToPlay()
player.play()

} catch let error as NSError {
print(error.description)
}
}

Swift 3

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }

do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)

let player = try AVAudioPlayer(contentsOf: url)

player.play()

} catch let error {
print(error.localizedDescription)
}
}

Swift 4 (iOS 13 compatible)

import AVFoundation

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

Make sure to change the name of your tune as well as the extension.
The file needs to be properly imported (Project Build Phases > Copy Bundle Resources). You might want to place it in assets.xcassets for
greater convenience.

For short sound files you might want to go for non-compressed audio formats such as .wav since they have the best quality and a low cpu impact. The higher disk-space consumption should not be a big deal for short sound files. The longer the files are, you might want to go for a compressed format such as .mp3 etc. pp. Check the compatible audio formats of CoreAudio.


Fun-fact: There are neat little libraries which make playing sounds even easier. :)

For example: SwiftySound

start playing audio from a background task via AVAudioPlayer in Xcode

From what I've learned after writing an player App, it seems that you can not start playing audio when your App is already in background for longer than X seconds, even if you have configured everything right.

To fix it, you have to use background task wisely.
The most important thing is that you must NOT call endBackgroundTask immediately after playSoundFile. Delay it for about 5-10 seconds.

Here is how I managed doing it for iOS6 and iOS7.

1, Add audio UIBackgroundModes in plist.

2, Set audio session category:

3, Create an AVQueuePlayer in the main thread and enqueue an audio asset before the App enter background.

*For continues playing in background (like playing a playlist)*

4, Make sure the audio queue in AVQueuePlayer never become empty, otherwise your App will be suspended when it finishes playing the last asset.

5, If 5 seconds is not enough for you to get the next asset you can employ background task to delay the suspend. When the asset is ready you should call endBackgroundTask after 10 seconds.

Recording Audio on iOS 7 with AVAudioRecorder and keeping sound file saved for playback on App Restart

So after digging around similar topics I came across this thread in which user Paul Brady states that the following code is overriding the file and thus should be removed so when the app reopens, the file is accessible: "[recorder prepareToRecord]"

Problems Recording and Playing Back Audio Simultaneously

The appropriate way to do this is via AudioUnit APIs, even though it seems like a common scenario which should be handled by higher level APIs.

I wrote a small demo app using AudioUnit. You're free to try it our and modify it for suiting your purpose. The demo app does record audio and play it simultaneously, but it's recommended to use a ear phone to see the effect.

Playback and Recording simultaneously using Core Audio in iOS

The RemoteIO Audio Unit can be used for simultaneous record and play. There are plenty of examples of recording using RemoteIO (aurioTouch) and playing using RemoteIO. Just enable both unit input and unit output, and handle both buffer callbacks. See an example here

Sound not playing with AVAudioPlayer

SOLVED.

1.- Check if your file has been added to "Copy Bundle Resources" in Build Phases.
Copy Bundle Resources

2.- ViewController.m

#import <AVFoundation/AVAudioPlayer.h>

@interface ViewController ()
@property (nonatomic, strong) AVAudioPlayer *theAudio;
- (IBAction)pushBell;
@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

NSString *soundPath =[[NSBundle mainBundle] pathForResource:@"beep-beep" ofType:@"caf"];
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];

NSError *error = nil;
self.theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
}

- (IBAction)pushBell {
[self.theAudio play];
}

3.- Connect the IBAction to your button in Interface Builder.

Done.



Related Topics



Leave a reply



Submit