Can AVPlayer place MP3 files?
It does not list MP3 in the apple documentation.
Did u try using
[[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
to play the file
Yes it can play MP3.
Try reading the apple documentation here and specifically the section entitled "iOS Hardware and Software Audio Codecs"
Here is a complete sample.
myClass.h:
- #interface myClass : NSObject \<AVAudioPlayerDelegate\> ...
myClass.m:
localPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:newAudioURL error:nil]; [localPlayer
setDelegate:self];
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)playedPlayer successfully:(BOOL)flag {
NSLog(#"releasing");
[playedPlayer release];
NSLog(#"released"); }
Related
I’m trying to make a small iPhone application with some buttons to play WAV sounds.
My buttons works, but I have a small latency (~ 0,5 sec).
This is my .m file :
#import "buttonSoundViewController.h"
#implementation buttonSoundViewController
//#synthesize player;
-(IBAction) playSoundA:(id)sender{
NSString *path = [[NSBundle mainBundle] pathForResource:#"a" ofType:#"wav"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
-(IBAction) playSoundB:(id)sender{
NSString *path = [[NSBundle mainBundle] pathForResource:#"b" ofType:#"wav"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[player release];
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
}
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
}
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
[audioPlayer release];
[super dealloc];
}
#end
How can I avoid this latency between playing different sounds?
Using AudioServices is indeed much quicker for small sounds (less than 30 seconds). The required code isn't very long either (but it requires some good old C).
#import <AudioToolbox/AudioServices.h>
SystemSoundID soundID = 0;
NSString* str = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
CFURLRef soundFileURL = (CFURLRef)[NSURL URLWithString:str ];
OSStatus errorCode = AudioServicesCreateSystemSoundID(soundFileURL, &soundID);
if (errorCode != 0) {
// Handle failure here
}
else
AudioServicesPlaySystemSound(soundID);
Also you can optimize your sounds (reduce their size) with the following terminal command:
afconvert mysound.caf mysoundcompressed.caf -d ima4 -f caff
You could simplify things a lot by using system sounds. Look up: AudioServicesCreateSystemSoundID in the documentation. There is also a "System Sound Services Reference Document" that talks about that and other related functions. This is a simple and efficient way to play short sounds. Not sure if it will solve your latency issues but its a good start. You may also try using some different sound file types. Perhaps there is an issue with how it was or was not compressed.
Maybe you could look at AppSoundEngine. It addresses latency and greatly simplifies using of System Sound Services, because it is objective-c wrapper for SystemSoundID and associated C functions.
You can not get acceptable latency (<10 ms) from AVAudioPlayer. System Sound Services is the way to go.
From the Apple Docs grab the SoundEffect class in project BubbleLevel
SoundEffect is a simple Objective-C wrapper around Audio Services
functions that allow the loading and playing of sound files.
Classes/SoundEffect.m
this will make playing files as easy as
SoundEffect *soundEffect = [SoundEffect soundEffectWithContentsOfFile:#""]
[soundEffect play];
it will also handle memory deallocation. AudioServicesDisposeSystemSoundID(soundID);
One simple fix would just be to do the AVAudioPlayer alloc init for the 2 sounds in your buttonSoundViewController's init method. Then those 2 audio players will already be ready to play in your button delegates.
The fastest way to play sounds is to use the RemoteIO Audio Unit, but that's a far more advanced and complicated looking API.
I want to play sound in my application for that I am using .mp3 file type. It is working fine in Simulator but when I am lunching it to my device it is not working and not producing any sound can any one help me why it is not working on device or which file format is better to play audio file in iPhone and iPad?
NSURL *tapSound = [[NSBundle mainBundle] URLForResource: [NSString stringWithFormat:#"%#",SoundFileName] withExtension: #""];
// Store the URL as a CFURLRef instance
self.soundFileURLRef = (CFURLRef) [tapSound retain];
// Create a system sound object representing the sound file.
AudioServicesCreateSystemSoundID (
soundFileURLRef,
&soundFileObject
);
AudioServicesPlaySystemSound (soundFileObject);
Above is mine code to play sound
Thank you.
The system sound IDs won't play if the device is muted, so this is possibly the cause. (They're only really for the purpose of user interface effects such as alerts, etc. as per the official documentation.)
As such, I'd be tempted to use the AVAudioPlayer style approach. As a sample (no pun intended) implementation:
// *** In your interface... ***
#import <AVFoundation/AVFoundation.h>
...
AVAudioPlayer *testAudioPlayer;
// *** Implementation... ***
// Load the audio data
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"sample_name" ofType:#"wav"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
NSError *audioError = nil;
// Set up the audio player
testAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
[sampleData release];
if(audioError != nil) {
NSLog(#"An audio error occurred: \"%#\"", audioError);
}
else {
[testAudioPlayer setNumberOfLoops: -1];
[testAudioPlayer play];
}
// *** In your dealloc... ***
[testAudioPlayer release];
You should also remember to set the appropriate audio category. (See the AVAudioSession setCategory:error: method.)
Finally, you'll need to add the AVFoundation library to your project. To do this, alt click on your project's target in the Groups & Files column in Xcode, and select "Get Info". Then select the General tab, click the + in the bottom "Linked Libraries" pane and select "AVFoundation.framework".
I honestly would suggest using AVAudioPlayer instead of this, but you could try using this alternate code instead. In your example it looks like you forgot to include the extension, which might be the problem also. The simulator is more lenient on naming, so if you forgot the extension it might play on the simulator and not a device.
SystemSoundID soundFileObject;
CFURLRef soundFileURLRef = CFBundleCopyResourceURL (CFBundleGetMainBundle (),CFSTR ("sound"),CFSTR ("mp3"),NULL );
AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject );
AudioServicesPlaySystemSound (soundFileObject);
Is it possible to pick media items using MPMediaPickerController and then load them into an AVAudioPlayer object?
If MPMusicPlayerController doesn't meet your needs, you can copy the audio to your local bundle so you can use AVAudioPlayer.
EDIT
You basically have three options for playing audio from the user's iPod library: MPMediaPlayer, AVPlayer and AVAudioPlayer.
Here are examples for MPMediaPlayer and AVPlayer:
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker
didPickMediaItems: (MPMediaItemCollection *) collection {
MPMediaItem *item = [[collection items] objectAtIndex:0];
NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
[self dismissModalViewControllerAnimated: YES];
// Play the item using MPMusicPlayer
MPMusicPlayerController* appMusicPlayer = [MPMusicPlayerController applicationMusicPlayer];
[appMusicPlayer setQueueWithItemCollection:collection];
[appMusicPlayer play];
// Play the item using AVPlayer
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:url];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[player play];
}
If you need to use AVAudioPlayer for some reason, or you need access to the audio file's actual audio data, you have to first copy the audio file to your app's directory and then work with it there. The AVAsset + AVPlayer stuff is the closest analogy to ALAsset if you're used to working with photos and videos.
Just wanted to say that it appears that in iOS 6 and 7, AVAudioPlayer can play file URLs directly from the iPod without having to copy the audio data into your app directory as Art suggested.
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) collection {
MPMediaItem *item = [[collection items] objectAtIndex:0];
NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
// Play the item using AVPlayer
self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[self.avAudioPlayer play];
}
I wanted to add (and I can't comment on SO yet) that it seems like in iOS 8, and perhaps before, songs that are stored on iCloud do not have a value for the property assetURL and return null for [npItem valueForProperty:MPMediaItemPropertyAssetURL].
Here is a sample output:
MPMediaItem *npItem = self.musicPlayerController.nowPlayingItem;
NSLog(#"Song Title: %#\n assetURL: %#\n Cloud Item: %d", npItem.title, [npItem valueForProperty:MPMediaItemPropertyAssetURL], npItem.cloudItem)
// Log Output
Song Title: Time We Had
assetURL: (null)
Cloud Item: 1
Song Title: The Quiet
assetURL: ipod-library://item/item.m4a?id=1529654720874100371
Cloud Item: 0
I think you'll find that the [NSBundle mainBundle] is READ-ONLY. It's not possible to write files into the APP, therefore AVAudioPlayer will not work for iPod-Library MPMediaItems!
I have a button on a UIImagePicker overly , and I want it to make some sound when clicked.
To do so, I have in my project resources a sound in m4a and mp3 formats (for test purpose).
I try to play the sound by many ways, trying alternatively with m4a and mp3 formats, but nothing goes out of the iPhone (not the simulator).
The Frameworks are include in the project.
Here is my sample code :
#import <AudioToolBox/AudioToolbox.h>
#import <AVFoundation/AVAudioPlayer.h>
- (IBAction) click:(id)sender {
// Try
/*
SystemSoundID train;
AudioServicesCreateSystemSoundID(CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("TheSound"), CFSTR("mp3"), NULL), &train);
AudioServicesPlaySystemSound(train);
*/
// Try
/*
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource: #"TheSound" withExtension: #"mp3"] error:&error];
[audioPlayer play];
[audioPlayer release];
*/
// Try (works)
//AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
// Try
/*
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"TheSound" ofType:#"mp3"] isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
*/
NSLog(#"Clicked");
}
Could you tell me what is going wrong ?
You can't use an MP3 with Audio Services. It must be a WAV file of a certain subtype. As for AVAudioPlayer, it supports MP3 files but when AVAudioPlayer is deallocated it stops playback, and since you do so immediately after sending -play (by sending -release to balance the +alloc), you never hear anything.
So either convert the file to WAV, or hang onto your AVAudioPlayer long enough for it to play. :)
I've been looking for a while how to play sound on the iphone, and I think it's something along the lines of:
[[NSSound soundNamed:#"cat.mp3"] play];
But the NSSound is on the AppKit ... any suggestions ? I know there is a really simple answer to this, but today my searches are not rendering any result ...
the new AVFoundation class is the easiest way to play sound on the iPhone, though it is for firmware 2.2 only:
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[audioPlayer play];
you just need this import in the class that uses it:
#import <AVFoundation/AVAudioPlayer.h>
Audio Toolbox system sounds are great for short async playback.
// Initialize
CFBundleRef mainBundle;
mainBundle = CFBundleGetMainBundle ();
// Init each sound
CFURLRef tapURL;
SystemSoundID tapSound;
tapURL = CFBundleCopyResourceURL(mainBundle, CFSTR("tap"), CFSTR("aif"), NULL);
AudioServicesCreateSystemSoundID(tapURL, &tapSound);
// Play the sound async
AudioServicesPlaySystemSound(tapSound);
I haven't gotten MP3s to work with AudioServicesPlaySystemSound. But it plays AIF files perfectly.