【问题标题】:iOS sound playback volume not respecting volume change or muteiOS 声音播放音量不考虑音量变化或静音
【发布时间】:2012-09-25 20:23:05
【问题描述】:

这是我当前的代码

void playSound(NSString* myString) {

    CFBundleRef mainBundle = CFBundleGetMainBundle();
    NSString *string = myString;
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, 
                        (__bridge CFStringRef) string, CFSTR ("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);

}

它可以工作,但它不允许您更改设备上的音量或使用静音开关将其静音。启用这些功能的最简单方法是什么?谢谢。

【问题讨论】:

    标签: iphone ios volume


    【解决方案1】:

    为什么不使用AVFoundation?如果您只想播放简单的音效,那将是更好的选择,因为它是更高级别的 API。

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    
    // Assuming audioPlayer is an ivar.
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = -1;
    
    if (audioPlayer == nil)
        NSLog([error description]);             
    else 
        [audioPlayer play];
    

    AVAudioPlayer 应该尊重用户的音量设置。

    【讨论】:

    • 如何声明audioPlayer?
    • 好的,我这样做了,但是由于未捕获的异常'NSInvalidArgumentException',现在我得到了这个终止应用程序,原因:'*** -[NSURL initFileURLWithPath:]: nil string parameter'
    • 你必须学会​​调试你的代码和解释错误信息。阅读它所说的。在NSURL 行中,您的参数是nil。你唯一的参数是filePath,所以是nil。然后您转到pathForResource:ofType: 的文档并在返回值 下查看:“资源文件的完整路径名或nil 如果找不到文件。”您的文件名错误或文件丢失。
    • 这是我的声音所在文件夹的路径 ----- PROJECTNAME -> Supporting Files -> My Sounds -> 然后文件名为cow.wav,我有这个pathForResource :@"cow" ofType:@"wav"
    • 我不知道目标是什么,请澄清一下?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多