使用音频工具箱播放.wav [英] Play a .wav with Audio Toolbox

查看:95
本文介绍了使用音频工具箱播放.wav的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用音频工具箱播放.wav文件.到目前为止,我有: 但是我的文件无法播放.如果条件被正确触发,但是它不会播放. 如果文件不存在,它将打印错误消息.有什么提示是怎么回事吗?

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

推荐答案

您不能在告诉声音ID播放后立即处理它,因为这会导致播放停止.这就是为什么您一开始没有听到它的原因.

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.

您应该做的是在负责创建ID的任何对象(例如,视图控制器)的属性中保留对ID的引用.您可以在接口声明中这样声明它:

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

这不仅可以让您在以后知道使用完后(例如,在viewDidUnload中)正确处理它,而且还可以防止您每次从磁盘读取文件您想播放一次,因为每个ID都可以无限次播放.

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.

最后一个提示:您可以直接向捆绑资源请求URL,而不是请求字符串,然后将其转换为URL.

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]])
    // ...

这篇关于使用音频工具箱播放.wav的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆