Вопрос

I am trying to play a .wav file using Audio Toolbox. I have this so far: However my file will not play. The If condition is triggered right, however it doesn't play. It will print the error message if the file isn't there however. Any clue what is wrong?

-(void) playSound : (NSString *) fName : (NSString *) ext
{

    SystemSoundID audioEffect;
    NSString *path  = [[NSBundle mainBundle] pathForResource : fName ofType :ext];
    if ([[NSFileManager defaultManager] fileExistsAtPath : path])
    {
        NSURL *pathURL = [NSURL fileURLWithPath : path];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
        AudioServicesPlaySystemSound(audioEffect);
    }
    else
    {
        NSLog(@"error, file not found: %@", path);
    }
    AudioServicesDisposeSystemSoundID(audioEffect);;
}
Это было полезно?

Решение

You can't dispose of the sound ID immediately after telling it to play, since this causes the playback to stop. That's why you didn't hear it in the first place.

What you should do instead is hold a reference to the ID in a property on whatever object is responsible for creating it (e.g., a view controller). You'd declare it like this in your interface declaration:

@property(nonatomic, assign) SystemSoundID audioEffect;

...and subsequently assign to it like this:

AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &_audioEffect);

This will not only allow you to properly dispose of it at a later time when you know you're done with it (e.g. in viewDidUnload), but will also prevent you from having to read the file in from disk each time you want to play it back, since each ID can be played an unlimited number of times.

One final hint: you can ask for the URL to a bundle resource directly instead of requesting a string and then transforming it to a URL.

NSURL *audioURL = [[NSBundle mainBundle] URLForResource:fName withExtension:ext];
if([[NSFileManager defaultManager] fileExistsAtPath:[audioURL path]])
    // ...

Другие советы

I figured it out from Warrenm's comment. I had to delete the last line, as it was killing the sound milliseconds after it was set to play, and therefore can't be heard.

-(void) playSound : (NSString *) fName : (NSString *) ext
    {

        SystemSoundID audioEffect;
        NSString *path  = [[NSBundle mainBundle] pathForResource : fName ofType :ext];
        if ([[NSFileManager defaultManager] fileExistsAtPath : path])
        {
            NSURL *pathURL = [NSURL fileURLWithPath : path];
            AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
            AudioServicesPlaySystemSound(audioEffect);
        }
        else
        {
            NSLog(@"error, file not found: %@", path);
        }
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top