i'm working on little game, and i've got problem with background music. I use AVAudioPlayer to play loop music. It's look like below:
NSString *path = [[NSBundle mainBundle] pathForResource:#"background" ofType:#"ogg"];
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:path] error:&error];
NSLog(#"%#", [error description]);
[player setNumberOfLoops:-1];
player.delegate = self;
[player play];
I've got in Supproting Files file background.ogg, background.mp3, background.wav and no one plays. What is wrong with it?
And when i use NSLog to print description error i've got:
Error Domain=NSOSStatusErrorDomain Code=1954115647 "The operation couldn’t be completed. (OSStatus error 1954115647.)"
Please help.
Some times,just because your audio file's quality is not match what it need,such as sampling rate.Please check up whether your audio sampling rate is lower than 24kHz.
I have tested some audio,And I found that when the audio sampling rate is higher than 44kHz,it work great, but if it is lower than 44kHz & higher than 22kHz, the AudioToolbox can't play the sounds first while AVAudioPlayer can work some times. And if it is lower than 22kHz both them will can't play these audio files.(these audio's file format which I tested just "m4a","mp3","wav")
By the way,If you want to convert the low sampling rate audio to 44kHz "m4a" file use itunes,it also can't work.Don't waste your time on this.
That was so easy. There is one more thing. When you use e.g NSTimer you must ivalidate it in some place. When you use AVAudioPlayer you have to stop it in some place.
[player stop];
Related
I'm using SpriteKit for my Mac OS project with Objective C and I'm trying to play a certain sound over and over again when contact between two nodes occurs. I don't want the player to wait for the sound to complete before playing it again. The sound is only about 1 second long, but it repeats as fast as every 0.5 seconds. I've tried two different methods and they both have issues. I'm probably not setting something up correctly.
Method #1 - SKAction
I tried getting one of the sprites to play the sound using the following code:
[playBarNode runAction:[SKAction playSoundFileNamed:#"metronome" waitForCompletion:NO]];
The sound plays perfectly on time, but the sound is modified. It sounds like reverb (echo) was applied to it and it has lost a lot of volume as well.
Method #2 - AVAudioPlayer
Here's the code I used to set this up:
-(void) initAudio {
NSString *path = [NSString stringWithFormat:#"%#/metronome.mp3", [[NSBundle mainBundle] resourcePath]];
NSURL *metronomeSound = [NSURL fileURLWithPath:path];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:metronomeSound error:nil];
[_audioPlayer prepareToPlay];
}
Later on in code it is called like this:
[_audioPlayer play];
The issue with this one is that it seems to wait until it's completed playing the first time before playing the sound again. Basically it fails to play many times.
Am I setting this up incorrectly? How can I fix this? Thanks in advance.
Retry method 1, but instead of having the sprite play the sound, have the scene play the sound via
[self runAction:[SKAction playSoundFileNamed:#"metronome" waitForCompletion:NO]];
inside the game SKScene class
I'm working on an app in which I need to stream a large collection of audio files ranging from 5 to 15 seconds each.
I would like to reduce the load time between the files as much as possible.
Main Question:
Is there a way to start buffering the next file (through HLS) while the current one is playing the last segment?
Is AVQueuePlayer an appropriate solution for this on the iOS side?
A detailed explanation will be much appreciated, since I am new both to HTTP Live Streaming and the AV Foundation.
Related Question:
How do radio apps stream their audio with no lag between the songs?
Yes, AVQueuePlayer is an appropriate solution for playing a sequence of audio streamed from the internet via HTTP protocol.
I'm using AVQueuePlayer for quite a while now with excellent results and no lagging between songs. Here is a simple example on how to use AVQueuePlayer:
NSURL *url1 = [NSURL URLWithString:[urlsToPlay objectAtIndex:0]];
NSURL *url2 = [NSURL URLWithString:[urlsToPlay objectAtIndex:1]];
NSURL *url3 = [NSURL URLWithString:[urlsToPlay objectAtIndex:2]];
self.item1 = [[AVPlayerItem alloc] initWithURL:url1];
self.item2 = [[AVPlayerItem alloc] initWithURL:url2];
self.item3 = [[AVPlayerItem alloc] initWithURL:url3];
self.radioPlayerURLs = [[NSArray alloc] initWithObjects:self.item1,self.item2, self.item3, nil];
self.onDemandPlayer = [AVQueuePlayer queuePlayerWithItems:self.radioPlayerURLs];
[self.onDemandPlayer play];
For more details, please consulte Apple documentation:
AVFoundation
AVQueuePlayer
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self NextHeading]; // this plays an mp3 file
[self NextHeadingMeaning]; // this plays an Mp3 file
}
Only [self NextHeadingMeaning] method is called and NextHeading method is missed each time
-(IBAction) NextHeading{
[audio stop];
NSString *Filename = [[NSString alloc]initWithFormat:#"CH%#S%#",Heading,Meaning];
Filepath = [[NSBundle mainBundle]pathForResource:Filename ofType:#"mp3"];
audio = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:Filepath] error:NULL];
audio.delegate = self;
[audio play];
[Filename autorelease];
}
-(IBAction) NextHeadingMeaning {
[audio stop];
NSString *Filename = [[NSString alloc] initWithFormat:#"CH%#S%#",bold**Chapter**bold, Meaning];
Filepath = [[NSBundle mainBundle]pathForResource:Filename ofType:#"mp3"];
audio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Filepath] error:NULL];
audio.delegate = self;
[audio play];
[Filename autorelease];
}
Why is this happening and how can I resolve it ?
Please advice, thanks in advance.
You just used a single iVar (audio) as an player, and when you send NextHeading & NextHeadingMeaning message, the audio init with your sound_1.mp3 file firstly (it'll take some seconds if the mp3 file is big), then at the next moment (your first mp3 file might not inited, or has inited, but stopped followed by next message), you redo the init action with another mp3 file (sound_2.mp3), and finally, when the second mp3 file init done, audio plays sound_2.mp3. That's why you think the NextHeading is skipped.
So, to solve this problem, you can use a NSMutableArray iVar (e.g. audioPlayers), and create a local audio for both NextHeading & NextHeadingMeaning, and push it to audioPlayers.
And I think it is better to preload sound files if you can. :)
EDIT:
There's a playAtTime: method instead of play, you can delay the second audio player's playing time by this method, just like this:
[audioPlayer playAtTime:(audioPlayer.deviceCurrentTime + delay)];
delay is in seconds (NSTimeInterval).
There is no way that the first call is skipped, put a breakpoint in it or output something with NSLog() and you'll see. Most probable cause is that the first method doesn't do what you expect and this could be for various reasons - for example condition or specific timeout.
Edit:
After looking your code, it seems that you're missing some basic stuff like variable naming, variable scope and so. To simply make your code run, just replace the NSString *Filename.. string from the second method and probably it'll work. A better choice would be to visit Start Developing iOS Apps Today and follow the roadmap.
I'm pulling all of the video assets from ALAssetsLibrary (Basically everything that's being recorded from the native camera app). I am then running an enumeration on each video asset that does this to each video:
// The end of the enumeration is signaled by asset == nil.
if (alAsset) {
//Get the URL location of the video
ALAssetRepresentation *representation = [alAsset defaultRepresentation];
NSURL *url = [representation url];
//Create an AVAsset from the given URL
NSDictionary *asset_options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:asset_options];//[AVURLAsset URLAssetWithURL:url options:asset_options];
//Here is the problem
NSLog([NSString stringWithFormat:#"%i", [avAsset.tracks count]]);
NSLog([NSString stringWithFormat:#"%f", CMTimeGetSeconds(avAsset.duration)]);
}
NSLog is reporting that the AVAsset that I've gotten from my ALAsset has 0 tracks, and has a duration of 0.0 seconds. I checked the url, and it's "assets-library://asset/asset.MOV?id=9F482CF8-B4F6-40C2-A687-0D05F5F25529&ext=MOV" which seems correct. I know alAsset is actually a video, and the correct video, because I've displayed alAsset.thumbnail, and it's shown the correct thumbnail for the video.
All this leads me to believe there's something going wrong in the initialization for avAsset, but for the life of me, I can't figure out what's going wrong. Can anyone help me?
Update:
I think i've confirmed that the url being given to me by ALAssetRepresentation is faulty, which is weird because it gives me the correct thumbnail. I added this code in:
NSLog([NSString stringWithFormat:#"%i", [url checkResourceIsReachableAndReturnError:&error]]);
NSLog([NSString stringWithFormat:#"%#", error]);
It gives me this:
0
Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x19df60 {}
I'm still not sure what would cause that. The only thing I'm noticing is the url, which is "assets-library://asset/asset.MOV?id=9F482CF8-B4F6-40C2-A687-0D05F5F25529&ext=MOV" is different from what I've seen as I've been searching around for this. The one i've seen elsewhere looks more like "assets-library://asset/asset.MOV?id=1000000394&ext=MOV", with a number instead of an alphanumeric, dash separated name.
If it helps, I'm using XCode 4.2 Beta, and iOS5. Please let me know if you can think of anything. Thanks.
Okay, looks like it was a bug in the iOS5 beta v1. I upgraded to the newest and it worked. Thanks to those who took a look at my question.
long time reader, first time asker...
I am making a music app which uses AVAssetReader to read mp3 data from the itunes library. I need precise timing, so when I create an AVURLAsset, I use the "AVURLAssetPreferPreciseDurationAndTimingKey" to extract timing data. This has some overhead (and I have no problems when I don't use it, but I need it!)
Every thing works fine on iphone(4) and ipad(1). I would like it to work on my ipod touch (2nd gen). But it doesn't: if the sound file is too long (> ~7 minutes) then the AVAssetReader cannot start reading and throws an error ( AVFoundationErrorDomain error -11800. )
It appears that I am hitting a wall in terms of the scanter resources of the ipod touch. Any ideas what is happening, or how to manage the overhead of creating the AVURLAsset so that it can handle long files?
(I tried running this with the performance tools, and I don't see a major spike in memory).
Thanks, Dan
Maybe you're starting to read too son? As far as I understand, for mp3 it will need to go trough the entire file in order to to enable precise timing. So, try delaying the reading.
You can also try registering as an observer for some of the AVAsset properties. iOS 4.3 has 'readable' property. I've never tried it, but my guess would be it's initially set to NO and as soon as AVAsset has finished loading it gets set to YES.
EDIT:
Actually, just looked into the docs. You're supposed to use AVAsynchronousKeyValueLoading protocol for that and Apple provides an example
NSURL *url = <#A URL that identifies an audiovisual asset such as a movie file#>;
AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
NSArray *keys = [NSArray arrayWithObject:#"duration"];
[asset loadValuesAsynchronouslyForKeys:keys completionHandler:^() {
NSError *error = nil;
AVKeyValueStatus durationStatus = [asset statusOfValueForKey:#"duration" error:&error];
switch (durationStatus) {
case AVKeyValueStatusLoaded:
[self updateUserInterfaceForDuration];
break;
case AVKeyValueStatusFailed:
[self reportError:error forAsset:asset];
break;
case AVKeyValueStatusCancelled:
// Do whatever is appropriate for cancelation.
break;
}
}];
If 'duration' won't help try 'readable' (but like I mentioned before 'readable' requires 4.3). Maybe this will solve your issue.